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 patterns with threads for .NET 2.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 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 the 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 are not too many threads today, and the last blog entry is similar. So, I plan to present another Powerful Async Pattern for you in the next few blog entries. In the end, I will make the presenter a comparison of all of them.
Enjoy!
P ;).