Async vs. Await in C#
When To Use Async vs. Await
Notes
In C#, the runtime will automagically handle the async-ness of calling something that is awaitable. That is to say, calling something that you can await won’t necessarily block execution entirely, but you probably don’t want to do so on the main thread. There are also considerations when you want to “fire and forget” versus actually wait for the call you’re making to complete.
In general, these are the key points:
- If the call is awaitable, then await the call.
- If the call is not awaitable, then consider wrapping it in a
Taskso that the caller isn’t blocked. Consider async alternatives if the call does something external, however, like read/write to files or over a network. - If you use
ConfigureAwaiter(false), you might not come back on the same thread context as you left it on.
Other Information
It depends on what you are actually trying to do. You need to analyze the situation and see if your work is ‘IO-bound’ or ‘CPU-bound’.
IO-bound means you’re waiting on something external to your program to give you info. If you’re making a HTTP call or talking to the filesystem or a database, that’s external to your program, that’s IO-bound. You can’t make IO-bound work finish more quickly, because it’s not in your control. Note that I haven’t mentioned threads. That’s because threads have nothing to do with it.
CPU-bound means you have some complex work that you want to get through more quickly by splitting it up over threads/CPU cores/whatever.
For CPU-bound work, use
Task.Run(to ask the thread pool to maybe put it on another thread) or the Task Parallel Library (for multiple cores).For IO-bound work, use
async/await. Again, it won’t complete any quicker, but your program will be able to stay responsive while waiting for the external thing (database, HTTP call) to complete.
Microsoft also has some nice examples to refer to.