Free mag vol1 | Page 800

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING } InitializeComponent(); private void btnCallMethod_Click(object sender, EventArgs e) { this.Text = DoWork(); } private string DoWork() { Thread.Sleep(10000); return "Done with work!"; } } Now, given your work in this chapter, you know that if you were to run the program and click this button, you would need to wait 10 seconds before the text box control could receive keyword input. Furthermore, you will not see the title of the main window update with the message "Done with work!" for 10 seconds as well. If we were to use any of the previous techniques seen in this chapter to make our program more responsive, we would have a good deal of work ahead of us. However, under .NET 4.5, we can author the following C# code base: public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private async void btnCallMethod_Click(object sender, EventArgs e) { this.Text = await DoWork(); } // See below for code walkthrough... private Task DoWork() { return Task.Run(() => { Thread.Sleep(10000); return "Done with work!"; }); } } First, notice that our button’s Click event hander has been marked with the async keyword. This marks the method as a member to be called in a nonblocking manner. Also notice that the implementation of the event handler uses the await keyword before naming the method that will be called. This is important: if you decorate a method with the async keyword, but do not have at least one internal await-centric method call, you have essentially built a blocking, synchronous method call (in fact, you will be given a compiler warning to this effect). 745