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 pattern with Async CTP1 for .NET and C# 5.0. Example code is very similar except 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 than last entry except this time we are using async and await keywords, I modified number of threads in test to 0 because we do not know exactly how many threads are invoked by Async CTP1. And I have conclusion that this time code of RunAsync is very nice and everything is easy to understood. I was begin and end invocation synchronically by magic of Async CTP1 invoke that code in every CPU I had. I think that is the best one implementation of Powerfull Async Pattern.

Enjoy!

P ;).

Leave a Reply

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

*