[英]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.我有一个 function,只有在从异步 function 收到回调时才需要执行它。
Like喜欢
I call asynchronous function Stop()
and soon after that I call asynchronous function Start()
.我调用异步 function
Stop()
,不久之后我调用异步 function Start()
。
The Issue before Stop CallBack is received Start()
is called and thus I am getting issues.收到 Stop CallBack 之前的问题
Start()
被调用,因此我遇到了问题。 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.但是在我收到 Stop 回调之前,我的 start() function 被执行,从而给我带来了问题。
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();
}
}
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.由于这些看起来像成员函数,您可以添加一个事件成员变量(
ManualResetEvent
或AutoResetEvent
。然后在Stop()
方法中将事件设置为已发出信号。在调用 Stop() 和 Start() 之间等待为事件。
private AutoResetEvent _stopped = new AutoResetEvent(false);
public void SomeFunction()
{
Stop();
_stopped.WaitOne();
Start();
}
In the stop function you would do在停止 function 你会做
private void Stop()
{
try
{
// Your code that does something to stop
}
finally
{
_stopped.Set(); // This signals the event
}
}
If using a ManualResetEvent
-如果使用
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.