I wrote simple example on WinForm:
private async void button1_Click(object sender, EventArgs e)
{
await foo().ConfigureAwait(true);
textBox1.Text += "\r\n Current thread: " + Thread.CurrentThread.ManagedThreadId;
textBox1.Invalidate();
}
private async Task foo()
{
textBox1.Text += "Current thread: " + Thread.CurrentThread.ManagedThreadId;
HttpClient client = new HttpClient();
await await client.GetStringAsync("https://jsonplaceholder.typicode.com/todos/1").ContinueWith<Task>(async (p) =>
{
await Task.Delay(100_000).ConfigureAwait(true);
textBox1.Text += "\r\n Current thread SecondContinueWith: " + Thread.CurrentThread.ManagedThreadId;
}
).ConfigureAwait(true);
textBox1.Text += "\r\n Current thread: " + Thread.CurrentThread.ManagedThreadId;
}
This code write to textBox1 output: “Current thread: 1rn Current thread SecondContinueWith: 14rn Current thread: 1rn Current thread: 1” . But I expected that continuation in ContinueWith will capture WindowsFormsSynchronizationContext and will execute in UI Thread. But continuation print another ThreadId without debug mode and in Debug mode throw IvalidationException thus continuation execute in another thread from threadpool. Why continuation don’t capture context?When I miss context? Why continuation execute in another thread then UI thread?
Note: When I explicity use SynchronizationContext.SetSynchronizationContext in continuation , continuation execute in UI thread as expecting.