Using C# 5.0 to perform asynchronous operations
Using synchronous operations is really easy. Just call some operation, wait for it to return, and use the result. As we've seen, the problem is that slow operations block the calling (UI) thread or that thread does some hard CPU bound work; in both cases, the UI may become unresponsive. We have seen several ways to deal with that. These require running the long operation on a different thread, and when the results are finally available, marshal some code to update the UI.
The net result is code complexity, which grows quickly with more and more asynchronous operations happening. And if we consider more than one operation at a time, potential cancellations, adding timeouts, handling exceptions conveniently – code complexity climbs quickly.
C# 5.0 has a new feature related to calling operations running asynchronously and waiting efficiently for the result without all the required marshaling and code complexity. In this recipe, we'll take a brief...