Chapter 18. Asynchronous Language Features

The main new feature in C# 5.0 is 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 operating system 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 Windows 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 is a waste of resources, because they make the thread block until the I/O completes. Threads are somewhat expensive in Windows, so systems tend to get the best performance if they have a relatively small number of OS threads. Ideally, you would have only as many OS threads as 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 17 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 wasting resources by forcing a thread to sit and wait for I/O ...

Get Programming C# 5.0 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.