ASP.NET 4.5异步等待和Response.Redirect [英] ASP.NET 4.5 async-await and Response.Redirect
问题描述
使用async
-await
时是否有任何方法可以从Page_Load
(或任何其他ASP.NET事件)重定向?当然,Redirect
会抛出ThreadAbortException
,但是即使我用try
-catch
捕获它,它最终也会出现错误页面.如果我调用Response("url", false)
,它不会崩溃,但是我需要停止执行页面(渲染页面等),所以这不是解决方案.正如我注意到的,这两种方法的行为有所不同:
Is there any way to redirect from Page_Load
(or any other ASP.NET event) when using async
-await
? Of course Redirect
throws ThreadAbortException
but even if I catch it with try
-catch
it ends up with an error page. If I call Response("url", false)
it doesn't crash but I need to stop execution of the page (rendering the page etc.) so it's not the solution. And as I noticed these two methods act differently:
这以ThreadAbortException结尾(我假设任务同步结束):
This ends up with ThreadAbortException (I assume the task ends synchronously):
protected async void Page_Load()
{
await Task.Run(() => { });
Response.Redirect("http://www.google.com/");
}
此响应在Response.Redirect之后继续进行:
This one continues after Response.Redirect:
protected async void Page_Load()
{
await Task.Delay(1000);
Response.Redirect("http://www.google.com/");
}
我必须等待响应,但是我正在尝试,即使删除了await
关键字(因此Task在后台运行并且该方法继续),其结果也相同.唯一有用的是删除async
关键字-我认为async
仅启用await
,仅此而已?!
I must wait for the response but I was experimenting and even if I remove the await
keyword (so Task runs in background and the method continues) it ends up the same. Only thing that helps is to remove the async
keyword - I thought async
ONLY enables await
and nothing more?!
推荐答案
好的,我找到了如何处理它的答案.
OK, I found the answer how to deal with it.
我已经在我的基Page类中创建了一个Redirect方法包装器:
I've created a Redirect method wrapper in my base Page class:
protected void Redirect(string url)
{
this.isRedirecting = true;
Response.Redirect(url, false);
if (Context.ApplicationInstance != null)
Context.ApplicationInstance.CompleteRequest();
}
并覆盖Render
和RaisePostBackEvent
:
protected override void Render(HtmlTextWriter writer)
{
if (this.isRedirecting)
return;
}
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
if (!this.isRedirecting)
base.RaisePostBackEvent(sourceControl, eventArgument);
}
就可以了.在所有等待的任务完成之前,ASP.NET 4.5不会触发PreRenderComplete
事件(=在生命周期中不会继续).
That does the trick. ASP.NET 4.5 won't fire the PreRenderComplete
event (= won't continue in the life-cycle) until all awaited tasks are completed.
这篇关于ASP.NET 4.5异步等待和Response.Redirect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!