How to Sleep a thread until callback for asynchronous function is received?

前端 未结 2 651
孤城傲影
孤城傲影 2020-12-30 11:48

I have a function that needs to be executed only when a callback is received from asynchronous function.

Like

I call asynchronous function Stop()

2条回答
  •  余生分开走
    2020-12-30 12:03

    Since these look like member functions, you can add an event member variable (either a ManualResetEvent or an AutoResetEvent. Then in the Stop() method you set the event to signaled. In between the calls to Stop() and Start() you wait for the event.

    private AutoResetEvent _stopped = new AutoResetEvent(false);
    
    public void SomeFunction()
    {
         Stop();
         _stopped.WaitOne();
         Start();
    }
    

    In the stop function you would do

    private void Stop()
    {
        try
        {
             // Your code that does something to stop
        }
        finally
        {
             _stopped.Set();  // This signals the event
        }
    }
    

    If using a ManualResetEvent -

    private ManualResetEvent _stopped = new ManualResetEvent(false);
    
    public void SomeFunction()
    {
         Stop();
         _stopped.WaitOne();
         Start();
    }
    
    private void Stop()
    {
        try
        {
             // Your code that does something to stop
        }
        finally
        {
             _stopped.Set();  // This signals the event
        }
    }
    
    private void Start()
    {
        _stopped.Reset();
    
        // Your other start code here
    }
    

提交回复
热议问题