Monday, January 4, 2010

Thread Creation with ManualResetEvent

Use ManualResetEvent to synchronize the multiple threads that are running. In this example the main thread will wait for all the threads to complete before exiting the caller method by using ManualResetEvent.WaitAll.

In the code below, I created a pattern with thread creation. Remeber that creating a thread is quite expensive, so remember tha you shoul create a thread only when you know how many process you will be running simutaneously and it may take time to process meaning it may run for 10 seconds or more.

If you have more than 20 threads to be created then try to execute them in batch specially if these threads will take time to process. Let 20 threads to finish first before creating another new batch of threads. This pattern was demostrated in the code below, with some code comments.

But if you have multiple processes that may take only for a few seconds then maybe consider using ThreadPool, which I will be discussing in my next blog.

Code:



Output:



Note:

You will encounter an error when using ManualResetEvent.WaitAll with a single threaded method meaning when a method has a declared [STAThread]

See a good pattern on how to use ManualResetEvent with a Single Threaded Method.

No comments:

Post a Comment