async/await
is the contemporary and easiest way to do async programming whether or not the job is I/O-bound; whether or not the Task
requires a thread.
For example, it is great for WinForms or WPF because the main thread can await
a child task to calculate the number of times Miss Piggy had lunch in a year (a rather long and complex CPU-bound operation let's say) and when complete executes the next line immediately below. It makes your code so intuitive unlike classical async callbacks; WaitOne
s or other mechanisms and the juggling acts that go with it.
MSDN:
You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous programming. However, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.
Visual Studio 2012 introduces a simplified approach, async programming, that leverages asynchronous support in the .NET Framework 4.5 and the Windows Runtime. The compiler does the difficult work that the developer used to do, and your application retains a logical structure that resembles synchronous code. More...
OP:
I have read numerous times that async/await is for I/O bound tasks
Incorrect. async/await
is shorthand for async programming where the compiler does more of the work. It is not just for I/O-bound tasks. CPU-bound tasks generally use a thread pool thread.
CPU-bound tasks should be performed on a separate background thread.
Yes...but that doesn't mean you can't await
the Task
. CPU-bound tasks unlike I/O-bound tasks require a thread to operate and by definition a worker thread and so will grab one from the available thread pool.
However, when starting long-running CPU-bound work on a new thread using Task.Run, you then have to await it at some point
You don't have to await
a Task
, such tasks would be known as fire-and-forget. The await
doesn't actually start it either, tasks are "hot". However by not awaiting, you run the risk of the task not completing when the application exits. e.g. a console app firing off a Task
and not awaiting it then exiting.
So aren't we using async/await here for a CPU-bound task too?
That's right, you can use it for any Task
whether it is I/O-bound or not.
More