I think you might misunderstand the purpose of
Parallel.For()
. It is not to execute tasks in the background but merely in parallel. To be fair, the
MSDN article[
^] doesn't state that outright, but it says:
Quote:
Executes a for (For in Visual Basic) loop in which iterations may run in parallel.
This does imply that even parallelism is not guaranteed (I know they are becoming rare but think of single core CPUs) and the calling thread may actually be used for loop execution. Furthermore,
For()
returns a
ParallelLoopResult
[
^] which doesn't give you any way of cancelling or waiting for completion (notice how
IsCompleted
indicates
premature completion) which would be unusual at best for an asynchronous API. Finally, a short test easily confirms this behavior:
static void Main(string[] args)
{
Console.WriteLine("Invoking Parallel.For() on thread {0}",
Thread.CurrentThread.ManagedThreadId);
Parallel.For(0, Environment.ProcessorCount, i =>
{
Thread.Sleep(1000);
Console.WriteLine(" Wasted 1 sec on thread {0}",
Thread.CurrentThread.ManagedThreadId);
});
Console.WriteLine("Parallel.For() returned on thread {0}",
Thread.CurrentThread.ManagedThreadId);
Console.ReadKey(true);
}
The last two lines will not execute until the completion of the loop. Long story short, what you are really looking for is
Task
[
^] (or some other way of running code asynchronously like
QueueUserWorkItem()
[
^] or spinning up your own background thread).