I have a ConcurrentBag collection, and for every item in this, i do a task for do some work.
I know that Parallel.ForEach with ConcurrentBag is thread safe, but i never done parallelism in this way.
My code looks like this
public void Work(IList<MyModel> data)
{
var tasks = new ConcurrentBag<Task>();
var safeData = new ConcurrentBag<MyModel>(data);
foreach (var item in safeData )
{
var task = Task.Factory.StartNew(() => SomeTask(item));
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
}
So, this code is thread safe?
Thanks
EDIT: Maybe this question could be: "item" will be thread safe or could change his value between iterations?
EDIT 2: I refer a if this code could fall in this problem.
Edit 3: In this question, "Wonko the sane" is having a problem when he works directly with a loop variable. I thought that this problem could be corrected using ConcurrentBag, but in some answers, tell me that i don't need ConcurrentBag at all. So:
Is a good idea use directly a loop variable?
When is recomended copy the value to another variable?
Is safe to work directly with a loop variable from ConcurrentBag?