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

前端 未结 2 648
孤城傲影
孤城傲影 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:13

    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();
        }
    
    }
    

提交回复
热议问题