The Powerful Async Pattern in .NET 4.0 with Parallel

Hi, in my blog entry The Powerful Async Pattern in .NET 1.1 without TPL and Async CTP1 I wrote about async pattern in .NET 1.1. And today I would like to show pattern with parallel for .NET 4.0. Example code is very similar except RunAsync method that I will show below.

public int[] RunAsync(int count) {
  int[] result = new int[count];

  Parallel.For(0, count,
  i =>
  {
    int arg = i + 1;
    result[i] = Invocation(arg);
  });

  return result;
}

And below is an output with results.

Invoker end status 8257, 1193 ms 01 threads, invocation sync. 
Invoker end status 8257, 0745 ms 00 threads, invocation async.
Invoker end status 8257, 1310 ms 01 threads, invocation sync.
Invoker end status 8257, 0818 ms 00 threads, invocation async.
Invoker end status 8257, 1233 ms 01 threads, invocation sync.
Invoker end status 8257, 0701 ms 00 threads, invocation async.
Invoker end status 8257, 1138 ms 01 threads, invocation sync.
Invoker end status 8257, 0567 ms 00 threads, invocation async.
Invoker end status 8257, 1150 ms 01 threads, invocation sync.
Invoker end status 8257, 0532 ms 00 threads, invocation async.
Invoker end status 8257, 1048 ms 01 threads, invocation sync.
Invoker end status 8257, 0609 ms 00 threads, invocation async.
Invoker end status 8257, 1330 ms 01 threads, invocation sync.
Invoker end status 8257, 0540 ms 00 threads, invocation async.
Invoker end status 8257, 1383 ms 01 threads, invocation sync.
Invoker end status 8257, 0748 ms 00 threads, invocation async.
Invoker end status 8257, 1104 ms 01 threads, invocation sync.
Invoker end status 8257, 0548 ms 00 threads, invocation async.
Invoker end status 8257, 1068 ms 01 threads, invocation sync.
Invoker end status 8257, 0532 ms 00 threads, invocation async.
Press any key to continue...

So, as you can see results are similar then last entry except this time we are using Parallel, I modified number of threads in test to 0 because we do not know exactly how many threads are invoked by Parallel class. And I have conclusion that this time code of RunAsync is very nice and clean.

Best wishes,

P ;).

Leave a Reply

Your email address will not be published. Required fields are marked *

*