I am using System.Threading.Tasks.Parallel.For
to do some heavyweight processing.
My code is:
int count = 10;
List<MyObj> results = new List<MyObj>();
Parallel.For(0, count, (index) =>
{
MyObj obj = GetMyObjMaybe();
if (obj != null)
results.Add(obj);
});
if (results.Contains(null))
{
//break here, and it does
}
//sometimes contains null objects
return results;
}
I wouldn't expect to be getting null in the List,开发者_如何学运维 but I am. I must be botching the use of index
somehow. Any ideas?
Your List<MyObj> results
is not thread-safe.
You are seeing nulls because results
could be invalid in many ways.
Either use a Thread-safe collection class or guard every access to results
yourself with a lock
statement.
精彩评论