In this chapter, we will cover the following recipes:
async
methodExceptions
in asynchronous codeasync
operation after timeout periodasync
tasks as they completeasync
solution with Task.WhenAll
async
for file accessWe've all seen client applications that do not respond to mouse events or update the display for noticeable periods of time. This delay is likely the result of code holding on to the single UI thread for far too long. Maybe it is waiting for network I/O or maybe it is performing an intensive computation. Meanwhile, the user is left sitting there waiting, as our application grinds to a halt. The answer to this problem is asynchrony.
How is the concept of asynchrony different from parallelism? Parallelism, with which you are quite familiar by this point in the book, is mainly about application performance. Parallelism enables developers to perform CPU intensive work on multiple threads at once, taking advantage of modern multi-core computer architectures. Asynchrony on the other hand, is a superset of concurrency. It includes concurrency as well as other asynchronous calls which are more I/O bound than CPU bound. Let's say you are saving a large file to your hard drive or you want to download some data from the server. These kinds of I/O bound tasks are ideal for asynchrony. Asynchrony is a pattern which yields control instantly, and waits for a callback or other notification to occur before continuing.
So, just do things using an asynchronous pattern and your UI responsiveness problems are solved, right? Well, yes, but there is one small problem. Asynchronous code is difficult, at least historically speaking. However, asynchrony is taking a huge leap forward in terms of usability. Microsoft has delivered this by building on the Task
functionality in .NET 4.5, as well as the addition of two new keywords to the .NET Framework: async
and await
.
In this chapter, we will walk through several recipes that show how to maintain a responsive UI or scalable services by using the new Task-based Asynchronous Pattern (TAP) of the .NET Framework 4.5.
3.141.193.148