Search code examples
c#manualresetevent

ManualEventReset - wait for any of both


Consider that I have passed two ManualEventReset instances

public void MyApiCall(ManualResetEvent ev1, ManualResetEvent ev2)
{
   //my code
}

Now, I have to 'WaitOne' for any of both (no matter which of them, I need to to continue as soon as one of them raised signal). It is possible without changing api?

One of the solutions is spin lock:

while (!ev1.WaitOne(0) && !ev1.WaitOne(0)) 
{
   Thread.Sleep(500);
}

But I wonder if there is some better solution.


Solution

  • You are looking for WaitHandle.WaitAny.

    Example:

    WaitHandle.WaitAny(new WaitHandle[] { ev1, ev2 });