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

回眸只為那壹抹淺笑 提交于 2019-11-30 09:37:09

This is when you want to use wait handles. Here is a short code sample to show one approach:

class AsyncDemo
{
    AutoResetEvent stopWaitHandle = new AutoResetEvent(false);
    public void SomeFunction()
    {    
        Stop();
        stopWaitHandle.WaitOne(); // wait for callback    
        Start();
    }
    private void Start()
    {
        // do something
    }
    private void Stop()
    {
        // This task simulates an asynchronous call that will invoke
        // Stop_Callback upon completion. In real code you will probably
        // have something like this instead:
        //
        //     someObject.DoSomethingAsync("input", Stop_Callback);
        //
        new Task(() =>
            {
                Thread.Sleep(500);
                Stop_Callback(); // invoke the callback
            }).Start();
    }

    private void Stop_Callback()
    {
        // signal the wait handle
        stopWaitHandle.Set();
    }

}

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!