如何休眠线程,直到收到异步函数的回调? [英] How to Sleep a thread until callback for asynchronous function is received?
问题描述
我有一个函数,只有当收到来自异步函数的回调时才需要执行。
像
我调用异步函数 Stop()
,然后我调用异步函数 Start()
p>
停止之前的问题收到CallBack 调用Start()
,因此我遇到问题。另外我不能分开调用两个函数像我不能这样做。
public void SomeFunction()
{
Stop();
}
public void Stop_CallBack(eventargs e)
{
Start();
}
我必须这样做:
public void SomeFunction()
{
Stop();
//做某事
Start();
}
但在我收到之前停止回调我的start()
任何人都可以帮我解决这个问题。
这是当你想使用等待句柄。这里是一个简短的代码示例显示一种方法:
class AsyncDemo
{
AutoResetEvent stopWaitHandle = new AutoResetEvent(false);
public void SomeFunction()
{
Stop();
stopWaitHandle.WaitOne(); //等待回调
Start();
}
private void Start()
{
// do something
}
private void Stop()
{
//这个任务模拟一个完成后将调用
// Stop_Callback的异步调用。在实际代码中,你可能会
//有这样的代替:
//
// someObject.DoSomethingAsync(input,Stop_Callback);
//
new Task(()=>
{
Thread.Sleep(500);
Stop_Callback(); //调用回调
})。Start();
}
private void Stop_Callback()
{
//等待句柄信号
stopWaitHandle.Set();
}
}
I have a function that needs to be executed only when a callback is received from asynchronous function.
Like
I call asynchronous function Stop()
and soon after that I call asynchronous function 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();
}
I have to do this:
public void SomeFunction()
{
Stop();
//Do something;
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();
}
}
这篇关于如何休眠线程,直到收到异步函数的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!