我有一个功能需要轮询某个服务器以获取我发送的作业的状态。它的形式是:
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
方法的主线程在方法完成执行之前终止,我将无法获得所需的状态更新。如何确保这些函数在主线程死亡之前完成执行。