The Powerful Async Pattern in .NET 4.0 with Tasks

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 tasks for .NET 4.0. The example code is very similar except for the RunAsync method that I will show below.

public int[] RunAsync(int count) {
  int[] result = new int[count];
  WaitHandle[] waits = new WaitHandle[maxThreads];
  for (int i = 0; i < count; ) {
    for (int t = 0; t < maxThreads && i < count; t++, i++) {
      waits[t] = new ManualResetEvent(false);
      new Task(new Action<object>(
      (twi) => {
        int ti = (int)twi;
        int arg = ti + 1;
        result[ti] = Invocation(arg);
        ((ManualResetEvent)waits[ti % maxThreads]).Set();
      }),i).Start();
    }
    WaitHandle.WaitAll(waits);
  }
  return result;
}

And below is an output with results.

Invoker end status 8257, 1169 ms 01 threads, invocation sync.
Invoker end status 8257, 0683 ms 06 threads, invocation async.
Invoker end status 8257, 1243 ms 01 threads, invocation sync.
Invoker end status 8257, 0631 ms 12 threads, invocation async.
Invoker end status 8257, 1196 ms 01 threads, invocation sync.
Invoker end status 8257, 0532 ms 19 threads, invocation async.
Invoker end status 8257, 1076 ms 01 threads, invocation sync.
Invoker end status 8257, 0526 ms 25 threads, invocation async.
Invoker end status 8257, 1049 ms 01 threads, invocation sync.
Invoker end status 8257, 0527 ms 32 threads, invocation async.
Invoker end status 8257, 1049 ms 01 threads, invocation sync.
Invoker end status 8257, 0530 ms 38 threads, invocation async.
Invoker end status 8257, 1053 ms 01 threads, invocation sync.
Invoker end status 8257, 0526 ms 44 threads, invocation async.
Invoker end status 8257, 1045 ms 01 threads, invocation sync.
Invoker end status 8257, 0526 ms 51 threads, invocation async.
Invoker end status 8257, 1050 ms 01 threads, invocation sync.
Invoker end status 8257, 0524 ms 57 threads, invocation async.
Invoker end status 8257, 1054 ms 01 threads, invocation sync.
Invoker end status 8257, 0523 ms 64 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 Tasks.

Wishes of all the best,

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.