Joining Wait Handles?

A little interesting here, I think. I have a class that is responsible for "multiplexing" several processing operations onto a fixed number of threads. A typical case is a producer / consumer problem, where each operation consists of a WaitHandle (in this case, a semaphore that keeps track of the number of items in the queue) and a delegate to call.

For example, if I have two manufacturers (A and B), producing items in two separate queues. Instead of creating two consumer flows for each producer (A1, A2, B1, B2), I multiplex four consumer flows into two flows. The code for this "multiplexer" works something like this (simplified bit):

WaitHandle[] waitHandles = new WaitHandle[2]; waitHandles[0] = NumberOfItemsFullInProducerAQueue; waitHandles[1] = NumberOfItemsFullInProducerBQueue; while(true) { int index = WaitHandle.WaitAny(waitHandles); if(index == 0) { // handle the item from queue A } else { // handle the item from queue B } } 

I am trying to extend this concept to a slightly more complicated example, when an action may require several wait commands before they are executed. I am wondering if there is any call to WaitHandle.Combine (waitHandle1, waitHandle2), which I can do to combine the two wait commands together into one wait descriptor. The end result will be something like:

 A,B,C,D are waitHandles E = Combine(A, B) F = Combine(C, D) waitHandles = { E, F } while(true) { int index = WaitHandle.WaitAny(waitHandles); if(index == 0) { } else { } } 

Extra points

Although this is not a requirement, it can also be very nice if combinations of wait commands may overlap. For example, something like this:

  A,B,C are waitHandles D = Combine(A, B) E = Combine(A, C) waitHandles = { D, E } // same as above from here 

Thanks for your help SO

+4
source share
1 answer

You might consider the new Barrier class in the .NET 4 TPL (with feedback up to 3.5 as part of Reactive Extensions . It is specifically designed for the scenarios you describe where you need to block execution until a few coordinating tasks reach a breakpoint You can also use the system task to create complex continuation paths, with one Task depending on the two previous completions, depending on the first completion of the task and, if the Exceptions occur at any point, having these Exceptions, aggregate data and communicated in a central place.

+1
source

Source: https://habr.com/ru/post/1333910/


All Articles