I find an interesting thing that when I tried to add an item into a dictionary in the Parallel loop. It throws a NullReferenceException
exception. I can fixed it, but I don't know why it throw that exception. I was wondering if someone can help me clear on that. Below is the source code, it's very simple.
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.
}
}