views:

48

answers:

1

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?

+5  A: 

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.

Henk Holterman
Thank you, Henk. I thought List<T> would be thread-safe for concurrent adding at least. A simple lock object fixed the problem. Thanks again.
bufferz
"You can accept an answer in 5 minutes." -SO. I'll be back :P
bufferz
@bufferz - in general, assume collections **might** be safe for concurrent reading but they almost never are safe for concurrent writing or mixed reads/writes. Then check your assumptions in the docs.
Steve Townsend