[英]Ensuring that the main thread doesn't die before execution of all an asyncronous method
I have a function which needs to poll a certain server to obtain the status of a job I sent it. 我有一个需要轮询特定服务器以获得我发送给它的作业状态的功能。 It is of the form:
它的形式为:
public Foo PollForJobOutcomeAsync(int pollSpan, Action<Foo> callback)
{
var caller = new AsyncMethodCaller((p, cb) =>
{
PollForJobOutcome(p);
cb(this);
});
caller.BeginInvoke(pollSpan, callback, null, null);
return this;
}
public void PollForJobOutcome(int pollSpan)
{
while (job not completed)
{
DoSomething();//send request to server, change job status according to response
Thread.Sleep(pollSpan);
}
}
Now unfortunately if the main thread calling the PollJobOutcomeAsync
method terminates before the method finishes execution I will not get the desired status update. 现在不幸的是,如果调用
PollJobOutcomeAsync
方法的主线程在该方法完成执行之前终止,则不会获得所需的状态更新。 How do I ensure that these functions finish execution before the main thread dies. 如何确保这些功能在主线程死亡之前完成执行。
You can make use of WaitHandle
here. 您可以在此处使用
WaitHandle
。
IAsyncResult result = caller.BeginInvoke(pollSpan, callback, null, null);
BeginInvoke
will return IAsyncResult
pass this to your main thread by return value or somehow then from your main thread call BeginInvoke
将返回IAsyncResult
通过返回值或通过某种方式从主线程调用将此值传递给您的主线程
result.AsyncWaitHandle.WaitOne();//main thread waits here till Async Operation completes
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.