Lock的使用:
相当于给字典创建一个锁,
多线程中使用一个字典去存,可能存在字典数据不全的问题,需要加这个方法。
//在多线程中使用字典等添加数据时,需要使用
private static readonly object Locker = new object();
lock (Locker)
{
dir.Add(index, buffer.Length);
}
例子:如果不使用这个方法,list.count就不是5000
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
object locker=new object();
List<string> list=new List<string>();
void Start()
{
for (int i = 0; i < 50; i++)
{
Thread thread = new Thread(Tes);
thread.Start();
}
}
void Tes()
{
for (int i = 0; i < 100; i++)
{
lock (locker)
{
list.Add(i.ToString());
}
}
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Debug.Log(list.Count);
}
}
}