The Powerful Async Pattern in .NET 2.0 with Threads

Hi, in my last 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 threads for .NET 2.0. Example code is very similar except 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 Thread(
      (twi) =>
        {
          int ti = (int) twi;
          int arg = ti + 1;
          result[ti] = Invocation(arg);
          ((ManualResetEvent)waits[ti % maxThreads]).Set();
        }){IsBackground = true}.Start(i);
   }

    WaitHandle.WaitAll(waits);
  }

  return result;
}

If you would like to test it you need last entry code and replace only this method to the new one. I would like to show below results of my benchmark.

Invoker end status 8257, 1139 ms 01 threads, invocation sync.
Invoker end status 8257, 0921 ms 06 threads, invocation async.
Invoker end status 8257, 1176 ms 01 threads, invocation sync.
Invoker end status 8257, 0842 ms 12 threads, invocation async.
Invoker end status 8257, 1120 ms 01 threads, invocation sync.
Invoker end status 8257, 0645 ms 19 threads, invocation async.
Invoker end status 8257, 1208 ms 01 threads, invocation sync.
Invoker end status 8257, 0826 ms 25 threads, invocation async.
Invoker end status 8257, 1116 ms 01 threads, invocation sync.
Invoker end status 8257, 0740 ms 32 threads, invocation async.
Invoker end status 8257, 1080 ms 01 threads, invocation sync.
Invoker end status 8257, 0650 ms 38 threads, invocation async.
Invoker end status 8257, 1115 ms 01 threads, invocation sync.
Invoker end status 8257, 1028 ms 44 threads, invocation async.
Invoker end status 8257, 1226 ms 01 threads, invocation sync.
Invoker end status 8257, 0732 ms 51 threads, invocation async.
Invoker end status 8257, 1052 ms 01 threads, invocation sync.
Invoker end status 8257, 0614 ms 57 threads, invocation async.
Invoker end status 8257, 1058 ms 01 threads, invocation sync.
Invoker end status 8257, 0597 ms 64 threads, invocation async.
Press any key to continue...

As you can see it is very efficient pattern too. There is not too much threads results today and in last blog entry are similar. So, I plan to present another Powerful Async Patterns for you in next few blog entries. At the end I will presenter comparison for all of them.

Enjoy!

P ;).

Leave a Reply

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

*