Chapter 17. Asynchronous Language Features
C# provides language-level support for using and implementing asynchronous methods. Asynchronous APIs are often the most efficient way to use certain services. For example, most I/O is handled asynchronously inside the OS kernel, because most peripherals, such as disk controllers or network adapters, are able to do the majority of their work autonomously. They need the CPU to be involved only at the start and end of each operation.
Although many of the services offered by operating systems are intrinsically asynchronous, developers often choose to use them through synchronous APIs (i.e., ones that do not return until the work is complete). This can waste resources, because they block the thread until the I/O completes. Threads have overheads, and if you’re aiming to get the best performance in a highly concurrent application (e.g., a web app serving large numbers of users), it’s usually best to have a relatively small number of OS threads. Ideally, your application would have no more OS threads than you have hardware threads, but that’s optimal only if you can ensure that threads only ever block when there’s no outstanding work for them to do. (Chapter 16 described the difference between OS threads and hardware threads.) The more threads that get blocked inside synchronous API calls, the more threads you’ll need to handle your workload, reducing efficiency. In performance-sensitive code, asynchronous APIs are useful, because instead of ...
Get Programming C# 10 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.