views:

72

answers:

2

There is a collection and each element of that collection is sent to a function where 5 threads have to work on it.

How to make 5 threads work on the passed item?

foreach(var item in collection)
{
   doSomeWork(item);
}

void doSomeWork(object item)
{
   //here i have to do something with the passed 'item' by using 5 threads
}
+1  A: 
foreach (var item in collection)
{
    for (var i = 0; i < 5; i++)
    {
        ThreadPool.QueueUserWorkItem(doSomeWork, item);
    }
}
Darin Dimitrov
In such case I got an error that the job on a certain file cannot be done because another process is using that file.
trnTash
What file are you talking about? You didn't mention anything like this in your question. You asked how to run 5 threads for each item in a given collection and I answered it. It is quite obvious that you cannot write to the same file from different threads/processes.
Darin Dimitrov
+1  A: 

In .NET 4 you can use Parallel LINQ:

Parallel.ForEach(collection, item => {
  // process each item
});

this will use the Parallel Extension's (PFX) heuristics to schedule one or more workers from the thread pool.

Richard
It's net 3.5, unfortunately :(
trnTash
i think you mean fortunately ??
f00