27
votes

I thought one of the points about async/await is that when the task completes, the continuation is run on the same context when the await was called, which would, in my case, be the UI thread.

So for example:

Debug.WriteLine("2: Thread ID: " + Thread.CurrentThread.ManagedThreadId);
await fs.ReadAsync(data, 0, (int)fs.Length);
Debug.WriteLine("3: Thread ID: " + Thread.CurrentThread.ManagedThreadId);

I would NOT expect this:

2: Thread ID: 10
3: Thread ID: 11

What gives? Why is the thread ID for the continuation different than the UI thread?

According to this article[^] I would need to explicitly call ConfigureAwait to change the behavior of the continuation context!

3
Can you write a minimal repro and post here or in a Gist?Stephen Cleary
Are you using ConfigureAwait(false) anywhere before this fragment? Or perhaps this code fragment is used inside an async lambda like this: await Task.Run(async () => { /* no synchronization context here! */ }) ?noseratio
Nope. Didn't even know about ConfigureAwait until I started googling this issue.Marc Clifton

3 Answers

39
votes

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

This "context" is SynchronizationContext.Current unless it is null, in which case it is TaskScheduler.Current. (If there is no currently-running task, then TaskScheduler.Current is the same as TaskScheduler.Default, the thread pool task scheduler).

It's important to note that a SynchronizationContext or TaskScheduler does not necessarily imply a particular thread. A UI SynchronizationContext will schedule work to the UI thread; but the ASP.NET SynchronizationContext will not schedule work to a particular thread.

I suspect that the cause of your problem is that you are invoking the async code too early. When an application starts, it just has a plain old regular thread. That thread only becomes the UI thread when it does something like Application.Run.

6
votes

The await expression will use the value of SynchronizationContext.Current to return control flow back to the thread on which it occurred. In cases where this is null it will default to the TaskScheduler.Current. The implementation relies solely on this value to change the thread context when the Task value completes. It sounds like in this case the await is capturing a context that isn't bound to the UI thread

-1
votes

By default, Windows Forms sets up the synchronization context when the first control is created.

So you can do like this:

[STAThread]
static void Main()
{
    Application.SetHighDpiMode(HighDpiMode.SystemAware);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    var f = new Form1();
    //var s=SynchronizationContext.Current;
    //var s2=TaskScheduler.Current;
    GetAsync();
    Application.Run(f);
}

static async Task<bool> GetAsync()
{
    MessageBox.Show($"thread id {Thread.CurrentThread.ManagedThreadId}");
    bool flag = await Task.Factory.StartNew<bool>(() =>
    {
       Thread.Sleep(1000);
       return true;
    });
    MessageBox.Show($"thread id {Thread.CurrentThread.ManagedThreadId}");
    return flag;
}