如何让线程休眠,直到收到异步函数的回调?

How to Sleep a thread until callback for asynchronous function is received?(如何让线程休眠,直到收到异步函数的回调?)
本文介绍了如何让线程休眠,直到收到异步函数的回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,只有在从异步函数接收到回调时才需要执行.

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

喜欢

我调用异步函数 Stop() 之后不久我调用异步函数 Start().

I call asynchronous function Stop() and soon after that I call asynchronous function Start().

收到停止回调之前的问题 Start() 被调用,因此我遇到了问题.我也不能分开调用两个函数就像我不能这样做.:

The Issue before Stop CallBack is received Start() is called and thus I am getting issues. Also I can not separate the calling of two functions Like I can not do this.:

public void SomeFunction()
{
    Stop();
}  

public void Stop_CallBack(eventargs e)
{
    Start();
}

我必须这样做:

public void SomeFunction()
{

  Stop();
  //Do something;

  Start();
}

但在我收到 Stop 回调之前,我的 start() 函数被执行,从而给我带来了问题.

but before I receive Stop call back my start() function is executed thus creating the problems for me.

谁能帮我解决这个问题.

Can anyone help me out how can I solve this issue.

推荐答案

这是你想要使用等待句柄的时候.下面是一个简短的代码示例来展示一种方法:

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

}

这篇关于如何让线程休眠,直到收到异步函数的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)