Unlike the legacy multi-threaded .net applications, wherein you can new up as many or atleast a couple threads till no more gain in application performance, in .Net 4.0 it is totally a discretion of task scheduler. This means that the code below - though it is naive - will not start a new THREAD each time when I am newing up Tasks in a for loop like below
for(int i = 0; i < 100 ; i++)
{
Task.Factory.StartNew(() =>
{ // Do Work.
}
}
The same is applicable to the statement below, but here it works the other way round
Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());
All we are doing above is to invoke the two methods DoSomeWork() and DoSomeOtherWork() in parallel. Now that does not mean that two different tasks will ALWAYS be created for this purpose, once the request goes to the taskscheduler It will know that it needs to spin two threads, not related to creating two new tasks.
Having said that it does not mean that if I have three methods like below , TaskScheduler will spin three threads. It might as well serve the request by two threads only.
Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork(), , () => DoSomeMoreOtherWork());
Taking another example, if you execute the code below and open the Parallel Tasks and Parallel Stacks window, you can clearly see that threads and Tasks are totally non-interrelated with TaskScheduler using it own optimisations to decide when to start a new thread.
Parallel.For
{
subtotal += nums[j];
return subtotal;
},
(x) => Interlocked.Add(ref total, x)
);
As msdn rightly says
"With the TPL, think in terms of tasks, not threads."
Happy Coding

The code selects the rows in a table into a collection depending on the where clause. I am fan of stuff like this !! Write me if you want me to explain :)



