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 a pattern with Parallel for .NET 4.0. The example code is very similar except for the RunAsync method, which 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 to the last entry except for this time, we are using Parallel, I modified several threads in the test to 0 because we do not know exactly how many threads are invoked by Parallel class. And I have concluded 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 *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.