trnTash
trnTash

Reputation: 307

Use threads during iteration

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
}

Upvotes: 1

Views: 106

Answers (2)

Richard
Richard

Reputation: 109210

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.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

foreach (var item in collection)
{
    for (var i = 0; i < 5; i++)
    {
        ThreadPool.QueueUserWorkItem(doSomeWork, item);
    }
}

Upvotes: 1

Related Questions