[英].NET Threading : How to wait for other thread to finish some task
Assume I have method void SomeMethod(Action callback) This method does some work in background thread and then invokes callback. 假设我有方法void SomeMethod(Action callback),此方法在后台线程中执行一些工作,然后调用回调。 The question is - how to block current thread until callback is called ?
问题是-如何在调用回调之前阻塞当前线程?
There is an example 有一个例子
bool finished = false;
SomeMethod(delegate{
finished = true;
});
while(!finished)
Thread.Sleep();
But I'm sure there should be better way 但我相信应该有更好的方法
You can use AutoResetEvent to signal when your thread is finished. 您可以使用AutoResetEvent在线程完成时发出信号。
Check this code snippet: 检查以下代码段:
AutoResetEvent terminateEvent = new AutoResetEvent(false);
bool finished = false;
SomeMethod(delegate
{
terminateEvent.Set();
});
terminateEvent.WaitOne();
Check for Thread.Join()
will work 检查
Thread.Join()
是否有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.