Reputation: 766
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!
Upvotes: 30
Views: 7654
Reputation: 509
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;
}
Upvotes: -1
Reputation: 754943
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
Upvotes: 6
Reputation: 456707
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
.
Upvotes: 44