简体   繁体   English

了解多个线程和EventWaitHandle

[英]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()? 因此,我知道该线程一旦到达WaitOne(),它将一直阻塞,直到调用Set()为止,但是如果有多个线程到达.WaitOne()怎么办? Will they all be blocked or just one? 他们会全部被阻止还是只被阻止? If Set() is called will it release all the threads or just one? 如果调用Set(),它将释放所有线程还是仅释放一个线程?

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? 编辑-我正在阅读更多内容,并尝试做一个后续问题:如果ManualResetEvent是什么实现了我上面描述的功能,当有多个线程同时等待时,它的行为如何? Would a AutoResetEvent release them one at a time with just one Set() call? AutoResetEvent是否仅通过一次Set()调用就一次释放它们?

AutoResetEvent : after one Set() called, only one thread will pass WaitOne() ; AutoResetEvent :在调用一个Set()之后,只有一个线程将传递WaitOne() other threads still waiting the second Set() . 其他线程仍在等待第二个Set()

ManualResetEvent : after one Set() called, thread will pass WaitOne() forever, unless you manually call Reset() . ManualResetEvent :调用一个Set()之后,线程将永远传递WaitOne() ,除非您手动调用Reset()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM