Search code examples
c#multithreadinglockingblocking

Understanding multiple threads and EventWaitHandle


I am trying to understand this code segment here I found online:

private EventWaitHandle wh = new AutoResetEvent();

private void WorkerThread() 
{
    while(true) 
    {
        wh.WaitOne();
        //Do work.
    }
}

public void StartWorking()
{
    wh.Set();
}

So I understand that the thread once it hits WaitOne() it will block until Set() is called, but what if multiple threads reach the .WaitOne()? Will they all be blocked or just one? If Set() is called will it release all the threads or just one?

Edit- I am reading more and trying it and a follow up question: If ManualResetEvent is what accomplishes what I described above how does it behave when there are multiple threads waiting at once? Would a AutoResetEvent release them one at a time with just one Set() call?


Solution

  • AutoResetEvent: after one Set() called, only one thread will pass WaitOne(); other threads still waiting the second Set().

    ManualResetEvent: after one Set() called, thread will pass WaitOne() forever, unless you manually call Reset().