开发者

Parallel.For synchronization with null objects

开发者 https://www.devze.com 2023-01-19 21:10 出处:网络
I am using System.Threading.Tasks.Parallel.For to do some heavyweight processing. My code is: int count = 10;

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

精彩评论

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