The Powerful Async Pattern in .NET and C# 5.0 with Async CTP1

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 Async CTP1 for .NET and C# 5.0. The example code is very similar except for the RunAsync method that I will show below.

public async Task<int[]> RunAsync(int count) {
  int [] result = new int[count];
  Task<int>[] tasks = new Task<int>[count];
  for (int i = 0; i < count; i++) {
    int arg = i + 1;
    tasks[i] = Task<int>.Factory.StartNew(() => Invocation(arg));
  }
  for (int i = 0; i < count; i++) {
    result[i] = await tasks[i];
  }
  return result;
}

And below is an output with results.

Invoker end status 8257, 1246 ms 01 threads, invocation Sync.
Invoker end status 8257, 0799 ms 00 threads, invocation Async.
Invoker end status 8257, 1290 ms 01 threads, invocation Sync.
Invoker end status 8257, 0582 ms 00 threads, invocation Async.
Invoker end status 8257, 1166 ms 01 threads, invocation Sync.
Invoker end status 8257, 0537 ms 00 threads, invocation Async.
Invoker end status 8257, 1089 ms 01 threads, invocation Sync.
Invoker end status 8257, 0529 ms 00 threads, invocation Async.
Invoker end status 8257, 1052 ms 01 threads, invocation Sync.
Invoker end status 8257, 0522 ms 00 threads, invocation Async.
Invoker end status 8257, 1090 ms 01 threads, invocation Sync.
Invoker end status 8257, 0525 ms 00 threads, invocation Async.
Invoker end status 8257, 1046 ms 01 threads, invocation Sync.
Invoker end status 8257, 0530 ms 00 threads, invocation Async.
Invoker end status 8257, 1048 ms 01 threads, invocation Sync.
Invoker end status 8257, 0523 ms 00 threads, invocation Async.
Invoker end status 8257, 1041 ms 01 threads, invocation Sync.
Invoker end status 8257, 0523 ms 00 threads, invocation Async.
Invoker end status 8257, 1045 ms 01 threads, invocation Sync.
Invoker end status 8257, 0525 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 async and await keywords, I modified several threads in test to 0 because we do not know exactly how many threads are invoked by Async CTP1. And I have a conclusion that this time code of RunAsync is very nice, and everything is easy to understand. I began and ended invocation synchronically by the magic of Async CTP1, invoking that code in every CPU I had. I think that is the best implementation of the Powerful Async Pattern.

Enjoy!

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.