Free mag vol1 | Page 805

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING All in all, it was a good deal of effort to simply compute the addition of two numbers on a secondary thread of execution! Here is the same project, now refactored using the new .NET 4.5 techniques under examination (I did not reprint the AddParams class here, but recall it simply had two fields, a and b, to represent the data to sum): class Program { static void Main(string[] args) { AddAsync(); Console.ReadLine(); } private static async Task AddAsync() { Console.WriteLine("***** Adding with Thread objects *****"); Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.ManagedThreadId); AddParams ap = new AddParams(10, 10); await Sum(ap); } Console.WriteLine("Other thread is done!"); static async Task Sum(object data) { await Task.Run(() => { if (data is AddParams) { Console.WriteLine("ID of thread in Add(): {0}", Thread.CurrentThread.ManagedThreadId); } } } }); AddParams ap = (AddParams)data; Console.WriteLine("{0} + {1} is {2}", ap.a, ap.b, ap.a + ap.b); The first thing I’d like to point out is that the code that was initially in Main() has been moved into a new method named AddAsync(). The reason was not only to conform to the expected naming convention, but this brings up a very important point:  Note The Main() method of an executable can not be marked with the async keyword. 750