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:
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/");
}
This one continues after Response.Redirect:
protected async void Page_Load()
{
await Task.Delay(1000);
Response.Redirect("http://www.google.com/");
}
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.
I’ve created a Redirect method wrapper in my base Page class:
And override
RenderandRaisePostBackEvent:That does the trick. ASP.NET 4.5 won’t fire the
PreRenderCompleteevent (= won’t continue in the life-cycle) until all awaited tasks are completed.