await Task doesn't capture Synchronization Context

319 Views Asked by At

I am trying to play around with ExecutionContext and SynchronizationContext.

I am using WinForms and .NET Framework 4.5.

Here's my code

private async void button1_Click(object sender, EventArgs e)
{
    var capturedExecutionContext = ExecutionContext.Capture();
    await Task.Run(() =>
    {
        ExecutionContext.Run(capturedExecutionContext, async (state) =>
        {
            // capturedSyncContext is not null
            var capturedSyncContext = SynchronizationContext.Current;

            await Task.Delay(3000);

            SynchronizationContext.Current.Post((state) => {
                lblHelloWorld.Text = "Nice";
            }, null);

        }, null);
    });
}

capturedSyncContext is not null as expected because the ExecutionContext is already captured it.

However, after the await statement, SynchronizationContext.Current returns null.

I believe that, the SynchronizationContext should be captured when you await a Task awaiter.

So why SynchronizationContext is null in this case ?

0

There are 0 best solutions below