开发者

Parallel.For synchronization with null objects

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜