1

I'm getting the basics down with async/await in C# and can't think of any reasons why someone is calling an async method that returns Task which they immediately await.

Would this not be better just to run the method synchronously to reduce the overhead of running the async method?

Or could it be the case of the method signature already being set that is dictating how it is being called?

Ian Mc
  • 29
  • 4
  • 5
    Because awaiting an asynchronous call doesn't mean blocking. `await` *doesn't* block the current thread. The thread is released as soon as the asynchonous method is called. Execution will continue on the original synchronization context when the call completes. In a UI environment, the synchronization context is the UI thread – Panagiotis Kanavos Feb 14 '19 at 15:02
  • The thread the task is running in doesn't block the main thread. In other words, should something go catastrophically wrong in the thread in the `DoWork()` method that's running as an async task, you can continue execution for cleanup or error reporting. – LeonidasFett Feb 14 '19 at 15:03
  • Take a look https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/ – Johnny Feb 14 '19 at 15:04
  • Furthermore, all IO on Windows is asynchronous. Blocking calls are *emulated*. Async operations can take advantage of that and use mechanisms like IO completion ports so they won't use any threads to await eg for a network response or a disk operation to complete – Panagiotis Kanavos Feb 14 '19 at 15:04
  • @LeonidasFett 1) The underlying long running work to be done may not be running CPU bound work in another thread *at all*. 2) If it *is* running CPU bound work in another thread, then the only situation in which it couldn't do any cleanup or error reporting would be something taking down *the whole process*, in which case no other thread could do either of those things either, or a stack overflow exception, which shouldn't be something that you'd need to plan to happen in a production environment. Any other type of problem and the thread would be able to still handle cleanup. – Servy Feb 14 '19 at 15:06
  • @IanMcNeish In other words, you're confusing "synchronous" with "serial". Synchronous means "blocks the calling thread"; serial means "one in a series" (i.e. one line of code executes at a time). `await` is a way of writing serial/imperative code but *without* blocking the calling thread, i.e., asynchronously. To put it another way, `await` pauses the method, not the thread. – Stephen Cleary Feb 14 '19 at 16:16
  • Thanks for all of the answers. The ones around returning the thread back to the UI makes sense to me, and after some testing I can see why people call the method and then await it instantly. – Ian Mc Feb 14 '19 at 16:52

0 Answers0