[英]PageAsyncTask Timeout - How to stop execution of async code
I'm trying to implement Async calls in a classic ASP.NET web page. 我正在尝试在经典的ASP.NET网页中实现异步调用。
I'm following the instructions I've found here and I can get it to call asynchronously but I don't know how to cancel the execution of the async method when the request times out (which I can easily do by pausing execution of my code at a breakpoint). 我正在按照我在这里找到的说明进行操作,我可以让它异步调用,但是我不知道如何在请求超时时取消异步方法的执行(我可以通过暂停执行来轻松地做到这一点代码在断点处)。
My code so far is as follows: 到目前为止,我的代码如下:
protected void Button_Click(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(OnBegin, OnEnd, OnTimeout, null);
Page.RegisterAsyncTask(task);
Page.AsyncTimeout = new TimeSpan(0, 0, 10);
Page.ExecuteRegisteredAsyncTasks();
}
protected delegate void AsyncTaskDelegate();
private AsyncTaskDelegate _dlgt;
public IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
_dlgt = new AsyncTaskDelegate(ExecuteAsyncTask);
IAsyncResult result = _dlgt.BeginInvoke(cb, extraData);
return result;
}
public void OnEnd(IAsyncResult ar)
{
_dlgt.EndInvoke(ar);
}
private void ExecuteAsyncTask()
{
MyObject obj = new MyObject();
var task = obj.CompleteAsync();
if (obj.Complete())
{
LabelResult.Text = "Success";
}
else
{
LabelResult.Text = "Failed";
}
}
public void OnTimeout(IAsyncResult ar)
{
_dlgt.EndInvoke(ar);//this does not work!
}
The main issue I have is that the code can "hang" at a certain point in the async method as I am calling an outside service and it can stop responding under certain situations. 我遇到的主要问题是,当我调用外部服务时,代码可以在异步方法中的某个位置“挂起”,并且在某些情况下它可以停止响应。
Even if I try to EndInvoke the request the async code still runs. 即使我尝试EndInvoke请求,异步代码仍然会运行。
Any help would be appreciated. 任何帮助,将不胜感激。
OK so I I've worked it out. 好,所以我已经解决了。 It has to do with cancellation tokens . 它与取消令牌有关 。
private System.Threading.CancellationTokenSource tokenSource = new System.Threading.CancellationTokenSource();
var task = System.Threading.Tasks.Task.Factory.StartNew(() => myObject.AsyncMethod(Request.QueryString, tokenSource.Token), tokenSource.Token);
And finally when the timeout occurs I simple do this: 最后,当发生超时时,我可以简单地这样做:
public void OnTimeout(IAsyncResult ar) { tokenSource.Cancel(); tokenSource.Token.ThrowIfCancellationRequested(); }
Voilà! 瞧!
This causes an exception which you then need to catch but at least this stops execution of any code. 这将导致您随后需要捕获的异常,但至少这会停止执行任何代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.