How to block until an event is fired in c#

前端 未结 4 687
孤街浪徒
孤街浪徒 2020-12-23 09:29

After asking this question, I am wondering if it is possible to wait for an event to be fired, and then get the event data and return part of it. Sort of like this:

4条回答
  •  孤城傲影
    2020-12-23 09:50

    You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:

    ManualResetEvent oSignalEvent = new ManualResetEvent(false);
    
    void SecondThread(){
        //DoStuff
        oSignalEvent.Set();
    }
    
    void Main(){
        //DoStuff
        //Call second thread
        System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
        oSecondThread.Start();
    
        oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
        oSignalEvent.Reset();
        //Do more stuff
    }
    

提交回复
热议问题