简体   繁体   中英

Task Parallel Library with QueueUserWorkItem

I am looking some code where I see this code:

Parallel.ForEach(names, new ParallelOptions { TaskScheduler = { }, MaxDegreeOfParallelism = Environment.ProcessorCount }, x =>
    {
        ThreadPool.QueueUserWorkItem(y =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("Processing {0} on thread {1}", names[i++],
                               Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(1000);
            });
    });

My question is, Do we have any advantage using the QueueUserWorkItem inside the Parallel.ForEach? For me it looks like we are creating 2 threads per each element, one in the ForEach and other in the QueueUserWorkItem.

This code doesn't makes much sense. Main feature of Paralell.ForEach is that it executes the code in paralell and waits till all the code completes execution. This code defeats the purpose of Paralell.ForEach . It is better to ask the author what he intended.

What this code does is, It starts the paralell loop inside every iteration it queues the work to ThreadPool.QueueUserWorkItem and returns immediately. It will not wait till all the work completes.

Your code is no better than the following code. Almost equal to a simple foreach loop.

foreach(var name in names)
{
    ThreadPool.QueueUserWorkItem(y =>
    {
        Thread.Sleep(1000);
        Console.WriteLine("Processing {0} on thread {1}", names[i++],
        Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(1000);
    });
});

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM