Free mag vol1 | Page 799

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING modThreeIsZero.Count())); } } catch (OperationCanceledException ex) { this.Invoke((Action)delegate { this.Text = ex.Message; }); }  Source Code The PLINQDataProcessingWithCancellation project is included under the Chapter 19 subdirectory. Asynchronous Calls Under .NET 4.5 We have covered a lot of terse material in this (rather lengthy) chapter. To be sure, building, debugging, and understanding complex multithreaded applications is a challenge in any framework. While the TPL, PLINQ, and the delegate type can simplify matters to some extent (especially when compared to other platforms and languages), developers are still required to be fairly savvy with the ins and outs of various advanced techniques. With the release of .NET 4.5, the C# programming language (and for that matter, the VB programming language) has been updated with two new keywords that further simplify the process of authoring asynchronous code. In contrast to all of the examples seen in this chapter, when you make use of the new async and await keywords, the compiler will generate a good deal of threading code on your behalf, using numerous members of the System.Threading and System.Threading.Tasks namespaces. A First Look at the C# async and await Keywords The async keyword of C# is used to qualify that a method, lambda expression, or anonymous method should be called in an asynchronous manner automatically. Yes, it’s true. Simply by marking a method with the async modifier, the CLR will create a new thread of execution to handle the task at hand. Furthermore, when you are calling an async method, the await keyword will automatically pause the current thread from any further activity until the task is complete, leaving the calling thread free to continue on its merry way. To illustrate, create a brand new Windows Forms application named FunWithCSharpAsync and import the System.Threading namespace into the initial form’s primary code file (I renamed my initial form to be MainForm). After you have done so, place a single Button control (named btnCallMethod) and a single TextBox control (named txtInput) on the designer surface, and configure any basic UI properties (colors, fonts, text) you want. Now, handle the Click event of the Button control, and within the event handler, call a private helper method named DoWork(), which forces the calling thread to wait for 10 seconds. Here is the story thus far: public partial class MainForm : Form { public MainForm() { 744