Microsoft .NET 4.0 introduces new "parallel enhancements" to its framework. I am wondering what the difference between making an application that uses the standard System.Threading functions versus the new parallel enhancements.
Here's a good channel9 I watched a while back on this topic: http://channel9.msdn.com/posts/philpenn/Parallel-Programming-with-NET-Parallel-Extensions/
Parallel Processing is just some fancy interface for auto creating threads. It is easier to use the parallel processing extension for most task.
The parallel framework uses the .NET threading model underneath which in turn builds on the Windows threading model. However, a lot of optimization has been done in the general framework to make the parallel library more efficient.
This blog has additional details.
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.