Chapter 4. Writing Async Methods
Now we know how great asynchronous code is, but how hard it is to
write? It’s time to look at the C# 5.0 async feature. As we saw previously
in What Async Does, a method marked async is allowed to contain the await keyword.
privateasyncvoidDumpWebPageAsync(stringuri){WebClientwebClient=newWebClient();stringpage=awaitwebClient.DownloadStringTaskAsync(uri);Console.WriteLine(page);}
The await expression in this
example transforms the method, so it pauses during the download, then
resumes when the download is done. This transformation makes the method
asynchronous. In this chapter, we’ll explore writing async methods like this
one.
Converting the Favicon Example to Async
We’ll now modify the favicon browser example from earlier to make
use of async. If you can, open the original version of the example (the
default branch) and try to convert it
by adding async and await keywords before reading any
further.
The important method is AddAFavicon, which downloads the icon, then adds
it to the UI. We want to make this method asynchronous, so that the UI
thread is free to respond to user actions during the download. The first
step is to add the async keyword to the
method. It appears in the method signature in the same way that the
static keyword does.
Then, we need to wait for the download using the await keyword. In terms of C# syntax, await acts as a unary operator, like the
! not operator, or the (type) cast operator. It is placed to the left ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access