Which ASP.NET lifecycle events can be async? Which ASP.NET lifecycle events can be async? asp.net asp.net

Which ASP.NET lifecycle events can be async?


Damian Edwards from the ASP.NET team gave this answer:

Async void event handlers in web forms are only supported on certainevents, as you've found, but are really only intended for simplistictasks. We recommend using PageAsyncTask for any async work of any realcomplexity.

Levi Broderick from the ASP.NET team gave this answer:

Async events in web applications are inherently strange beasts. Asyncvoid is meant for a fire and forget programming model. This works inWindows UI applications since the application sticks around until theOS kills it, so whenever the async callback runs there is guaranteedto be a UI thread that it can interact with. In web applications,this model falls apart since requests are by definition transient. Ifthe async callback happens to run after the request has finished,there is no guarantee that the data structures the callback needs tointeract with are still in a good state. Thus why fire and forget(and async void) is inherently a bad idea in web applications.

Thatsaid, we do crazy gymnastics to try to make very simple things likePage_Load work, but the code to support this is extremely complicatedand not well-tested for anything beyond basic scenarios. So if youneed reliability I’d stick with RegisterAsyncTask.

So I think the answer to my question is: "That's the wrong question."

The right question would be "How should I be async in my ASP.NET Web Forms application?" And the answer is to insert this snippet inside your aspx code-behind file:

this.RegisterAsyncTask(new PageAsyncTask(async cancellationToken => {    var result = await SomeOperationAsync(cancellationToken);    // do something with result.}));

This same trick works inside ASP.NET custom controls, just use this.Page.RegisterAsyncTask instead.


This page explains how life cycle event handling in asynchronous pages differs from those of synchronous pages in ASP.NET 2.0 (Figure 2 is especially helpful):

Wicked Code: Asynchronous Pages in ASP.NET 2.0

You may also find this SO question of use (it talks about the same error message):

async keyword and choice of the TaskScheduler