Async / Await in WebForms - How does the continuation continue until the page life cycle?

I tested async in WebForms, and this time my question is not how to do something, but how does something that works. This is my test code:

protected override void OnPreRender(EventArgs e)
{
    Response.Write("OnPreRender<Br>");
}
protected override void OnPreRenderComplete(EventArgs e)
{
    Response.Write("OnPreRenderComplete<Br>");
}
protected async override void OnLoadComplete(EventArgs e)
{
    Response.Write("OnLoadComplete<br>");
    var t1 = Task.Factory.StartNew(() => {
        System.Threading.Thread.Sleep(2000);
        return 1;
    });

    //This actually does run:
    Response.Write((await t1).ToString());
}

So my task pauses a bit and then writes the result. My question is: I would not expect this to work because the control was obtained from the OnLoadComplete method - I would expect the page to actually finish rendering and be returned to the client before my task ever returns.

Actual conclusion:

OnLoadComplete
OnPreRender
1OnPreRenderComplete

, , OnLoadComplete , OnPreRender , OnLoadComplete. , "1" , , , . , , , 10 , .

, WebForm - , . - , ? async/wait , , , , , .

+5
1

ASP.NET async .NET 4.5. , .

SynchronizationContext, , ASP.NET. -, , ASP.NET - (.NET 2.0 IIRC). , SynchronizationContext.OperationStarted.

ASP.NET SynchronizationContext , , ( SynchronizationContext.OperationCompleted). (, BackgroundWorker) SynchronizationContext .

, async void ( ) SynchronizationContext . , OnLoadComplete async void, , OperationStarted OperationCompleted, .

- ASP.NET , , . , , .

: ASP.NET , .NET 4.5 . ASP.NET 4.5 , . ASP.NET "pre" , . ASP.NET , async .

, ASP.NET 4.5 , async, , .

+11

All Articles