Why sync context is not working for await?

Viewed 976

This answer says

by default the await operator will capture the current "context" and use that to resume the async method.

I am trying this code in my console app:

static void Main(string[] args)
{
    Test().Wait();
}

private static async Task Test()
{
    var context = new SynchronizationContext();
    SynchronizationContext.SetSynchronizationContext(context);
    Console.WriteLine("Thread before: " + Thread.CurrentThread.ManagedThreadId);
    Console.WriteLine(await GetResultAsync());
    Console.WriteLine("Thread after: " + Thread.CurrentThread.ManagedThreadId);
}

private static async Task<string> GetResultAsync()
{
    return await Task.Factory.StartNew(() =>
    {
        Console.WriteLine("Thread inside: " + Thread.CurrentThread.ManagedThreadId);
        return "Hello stackoverflow!";
    });
}

... and get this out:

Thread before: 1
Thread inside: 3
Hello stackoverflow!
Thread after: 3

Why? And also how I should set sync context if I want to use the same thread after await?

2 Answers
Related