Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top