Monday, April 25, 2011

Array of WaitHandles (ManualResetEvent, AutoResetEvent, …) when waiting for operations to complete …

Reference :- http://blog.cincura.net/231837-array-of-waithandles-manualresetevent-autoresetevent-when-waiting-for-operations-to-complete/

Often, when you discover the beauty of multithreading and parallelism, you find a need to run some operations in parallel and wait for completion. Fairly common scenario. Although now, with .NET Framework 4, you can write it using Task Parallel Library‘s Parallel.Invoke, there are scenarios when you need to plug it in into some other methods/parameters, so you’ll do it yourself explicitly with threads or better to say ThreadPool.

The method I see from time to time looks basically like this:



Though it’s not wrong, except the ManualResetEvents are not Disposed, it’s suboptimal. You’re wasting resources creating array of these objects.

But if you think about it, you can write it better. Better in a way for scaling, performance and memory consumption.




I’m simply using one synchronization object (and using using statement ), because I’m really interested in only when all tasks are done (one stuff), and decrementing the total number of tasks every time one finishes. Using Interlocked class I’m sure no race condition will occur and I’ll get the right results. After it reaches zero I’m signaling I’m done and the method can continue.

Fewer resources, atomic operations usage … better/faster results.

No comments:

Post a Comment