【发布时间】:2018-12-04 15:56:38
【问题描述】:
当我尝试在 Parallel 循环中将项目添加到字典中时,我发现了一件有趣的事情。它会引发NullReferenceException 异常。我可以修复它,但我不知道它为什么会抛出该异常。我想知道是否有人可以帮助我澄清这一点。下面是源码,很简单。
class Program
{
private static Dictionary<int, Projection> CachedProjections =
new Dictionary<int, Projection>();
static void Main(string[] args)
{
var key = 3857;
Parallel.For(0, 400, _ =>
{
Projection projection = null; // If remove the null initialization it works well.
if (CachedProjections.ContainsKey(key))
{
projection = CachedProjections[key];
}
else
{
projection = new Projection();
CachedProjections[key] = projection;
}
});
Console.Read();
}
}
public class Projection
{
public Projection()
{
Thread.Sleep(10); // If comment out this line, it works well too.
}
}
【问题讨论】:
-
如果您想在多线程中使用字典,请使用
ConcurrentDictionary。 -
作为非静态方法试试
-
@FelixQuehl 应该完全相关
标签: c# .net dictionary task-parallel-library parallel.for