ASP.NET: Async Await with Web Forms Over Multiple Postbacks
Support for asynchronous procedures (using async
/ await
) is great in C# and VB languages, and works very well in desktop (WinForms, WPF, console and others) applications. But there are web applications, like based on ASP.NET Web Forms, where support for asynchronous procedures are much less exposed. Microsoft itself states, that support for asynchrony (using async
/ await
or other methods) is only limited to offload working threads, increase throughput and all asynchronous procedures must complete work before rendering phase (generating HTML).
But there are also much more useful scenarios, where asynchronous procedure is started in some postback, and completed in one of subsequent postbacks, so executing spans over multiple postacks. This allows for UI driven asynchronous processing, which is useful for most web apps. There are no examples or explanations how to do this, and some folks even state that this is impossible. Fortunately, this is possible, and here is how to do it.
Description of Method
Everything necessary to do this is to feed await
with non-started task, store this task and run it in some subsequent postback, on user’s request. This way, any execution of continuations will be limited only to page processing phase and we have full control over it. But for our needs, using tasks is not the best option. It is better to create custom awaiters similar to triggers, and switch them on user’s request, to continue execute of asynchronous procedures.
Credit: Tristan9