I thought I understood async/await but clearly not. I have something like this:
public async void SomeEventHandler()
{
await Task.Run(() => Method1());
}
private async Task Method1()
{
// Running on a worker thread here.
await SomeOtherMethodAsync();
// Now running on the UI thread.
}
As you can see from the above comments, Method1 starts out by running on a b/g thread as you would expect, having been called using Task.Run()
. However after the first await
, the remaining code then runs on the UI thread. I believe that adding ConfigureAwait(false)
to the "inner" async method call will prevent this from happening, but I don't understand the reason why it resumed on the UI thread in the first place. Why the UI thread and not the original (or other) b/g thread?
Surely "defaulting" to resuming on the UI thread is counter-productive, as there is potential to block the UI, which is exactly what async/await is trying to avoid.
In my real code, Method1 does a lot of CPU-bound stuff, hence why I call it using Task.Run; the method also calls numerous async I/O bound methods. Am I taking the right approach with my use of async/await and Task.Run?
Edit Just to clarify, I used breakpoints within Method1, and the Threads window, to see what thread the code was running on. Before the awaitable method call the Threads window highlighted a worker thread, while after the awaitable method call the "main thread" was highlighted.
Edit2 In response to @Aly's answer below, using the same debug text, this is what I see:
ManagedThreadID (Dispatcher): 11
ManagedThreadID (MainThread - before Task.Run(Method1)): 11
ManagedThreadID (Method1 - before SomeOtherMethodAsync): 14
ManagedThreadID (SomeOtherMethodAsync): 14
ManagedThreadID (Method1 - after SomeOtherMethodAsync): 11
ManagedThreadID (MainThread - after Task.Run(Method1)): 18