ASP.NET 4.5异步等待和Response.Redirect

编程入门 行业动态 更新时间:2024-10-03 14:21:31
本文介绍了ASP.NET 4.5异步等待和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("www.google/"); }

此响应在Response.Redirect之后继续进行:

This one continues after Response.Redirect:

protected async void Page_Load() { await Task.Delay(1000); Response.Redirect("www.google/"); }

我必须等待响应,但是我正在尝试,即使删除了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

本文发布于:2023-11-03 04:35:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   ASP   Redirect   Response

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!