开发者

Use threads during iteration

开发者 https://www.devze.com 2023-01-12 01:57 出处:网络
There is a collection and each element of that collection is sent to a function where 5 threads have to work on it.

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

精彩评论

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