문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top