我有一个函数需要轮询某个服务器以获取我发送它的作业的状态。它的形式为:
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);
}
}
现在不幸的是,如果调用PollJobOutcomeAsync
方法的主线程在方法完成执行之前终止,我将无法获得所需的状态更新。如何在主线程终止之前确保这些函数完成执行。
答案 0 :(得分:1)
您可以在此处使用WaitHandle
。
IAsyncResult result = caller.BeginInvoke(pollSpan, callback, null, null);
BeginInvoke
将返回IAsyncResult
通过返回值将其传递给主线程,或者以某种方式从主线程调用传递给
result.AsyncWaitHandle.WaitOne();//main thread waits here till Async Operation completes
希望这有帮助