Ale*_*dre 4 c# multithreading locking
为什么这个锁定测试不起作用?它正在抛出一个异常的控制台.Write该集合被修改了....
static List<string> staticVar = new List<string>();
static void Main(string[] args)
{
Action<IEnumerable<int>> assyncMethod = enumerator =>
{
lock (staticVar)
foreach (int item in enumerator)
staticVar.Add(item.ToString());
};
assyncMethod.BeginInvoke(Enumerable.Range(0, 500000), null, null);
Thread.Sleep(100);
Console.Write(staticVar.Count());
foreach (string item in staticVar)
{
}
}
Run Code Online (Sandbox Code Playgroud)
为了使锁有效,必须在访问集合的所有情况下使用它.无论是阅读还是写作.因此,您必须在枚举集合之前添加锁
例如
lock (staticVar) {
Console.Write(staticVar.Count());
foreach (string item in staticVar) {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
803 次 |
| 最近记录: |