CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
Note that AddAsync() is marked with the async token, and has defined an await context. As well, the
Sum() method is spinning off a new Task to perform the unit of work. In any case, lo and behold, when
we run the program, we find that 10 plus 10 is still indeed 20. Note, however, that we do have two unique
thread IDs (see Figure 19-6).
Figure 19-6. Our retrofitted System.Threading example, now using .NET 4.5 async features
Source Code The AddWithThreadsAsync project is included under the Chapter 19 subdirectory.
So, as you can see, the async and await keywords introduced with .NET 4.5 radically simplify the
process of invoking methods on a secondary thread of execution. While we have only worked through a
few examples of what can be done with this new functionality of the C# language, you are in a very good
position for further exploration.
Summary
This chapter began by examining how .NET delegate types can be configured to execute a method in an
asynchronous manner. As you have seen, the BeginInvoke() and EndInvoke() methods allow you to
indirectly manipulate a secondary thread with minimum fuss and bother. During this discussion, you
were also introduced to the IAsyncResult interface and AsyncResult class type. As you learned, these
types provide various ways to synchronize the calling thread and obtain possible method return values.
The next part of this chapter examined the role of the System.Threading namespace. As you learned,
when an application creates additional threads of execution, the result is that the program in question is
able to carry out numerous tasks at (what appears to be) the same time. You also examined several
manners in which you can protect thread-sensitive blocks of code to ensure that shared resources do not
become unusable units of bogus data.
This chapter then examined some new models for working with multithreaded development
introduced with .NET 4.0, specifically the Task Parallel Library and PLINQ. We wrapped things up by
examining the role of the new .NET 4.5 C# async and await keywords. As you have seen, these keywords
are using many types of the TPL framework in the background; however, the compiler does a majority of
the work to create the complex threading and synchronization code on our behalf.
751