Threading vs. Parallel Processing

Probably the most important difference between the Parallel Extensions and regular threading is the control flow.

A thread, created using new Thread(...) or ThreadPool.QueueUserWorkItem will terminate at a completely indeterminate point in time. If you write this code:

ThreadPool.QueueUserWorkItem(() =>
    {
        Thread.Sleep(1000);
        Console.WriteLine("Work Finished");
    });
Console.WriteLine("Item Queued");

The text Item Queued will appear right away, and Work Finished will be printed after about a 1 second delay.

On the other hand, if you write something similar using parallel extensions:

Parallel.For(0, 10, i =>
    {
        Thread.Sleep(1000);
        Console.WriteLine("Test {0}", i);
    });
Console.WriteLine("Finished");

What you’ll see in this case is a delay of 1 second before anything happens, then a slew of “Test” messages in a random order, and then the text Finished.

In other words, running tasks in parallel does not actually alter the program flow. It will run different tasks on different threads so that they can be executed on multiple CPU cores, in order to improve overall throughput of the program, but as far as the typical programmer is concerned, these tasks aren’t really running in the “background” as they would be with a thread. You don’t have to change your program’s structure or do anything special to be notified when the work completes. You have no control over what happens inside the parallel block, but you do know that the block will not return control until all parallel tasks are complete.

Although Parallel Extensions are great for this, it bears mentioning that PX are of no use whatsoever when you actually need to run a task in the background, such as implementing scheduler, or delegating to a worker thread in order to keep a UI responsive. You still need to use threads or async components for those.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)