开发者

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 开发者_Go百科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
}


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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜