4. Action<object> action = (object obj) => { Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId); }; // Construct an unstarted task Task t1 = new Task(action, "alpha"); // Cosntruct a started task Task t2 = Task.Factory.StartNew(action, "beta"); // Block the main thread to demonstate that t2 is executing t2.Wait(); // Launch t1 t1.Start(); Console.WriteLine("t1 has been launched. (Main Thread={0})", Thread.CurrentThread.ManagedThreadId); // Wait for the task to finish. You may optionally provide a timeout interval or a cancellation token to mitigate situations when the task takes too long to finish. t1.Wait(); // Construct an unstarted task Task t3 = new Task(action, "gamma"); // Run it synchronously t3.RunSynchronously(); // Although the task was run synchrounously, it is a good practice to wait for it which observes for // exceptions potentially thrown by that task. t3.Wait();
5.
6. public async Task<int> ExampleMethodAsync() { // . . . // At the await expression, execution in this method is suspended and, // if AwaitedProcessAsync has not already finished, control returns // to the caller of ExampleMethodAsync. int exampleInt = await AwaitedProcessAsync(); // . . . // The return statement completes the task. Any method that is // awaiting ExampleMethodAsync can now get the integer result. return exampleInt; }
7. // An event handler must return void. private async void button1_Click(object sender, RoutedEventArgs e) { textBox1.Clear(); // SumPageSizesAsync returns a Task. await SumPageSizesAsync(); textBox1.Text += "Control returned to button1_Click."; } // The following async lambda expression creates an equivalent anonymous // event handler. button1.Click += async (sender, e) => { textBox1.Clear(); // SumPageSizesAsync returns a Task. await SumPageSizesAsync(); textBox1.Text += "Control returned to button1_Click."; }
8. // The following async method returns a Task<T>. private async Task<byte[]> GetByteArrayAsync(Uri currentURI) { // Declare an HttpClient object. HttpClient client = new HttpClient(); // The GetAsync method returns a Task(Of T), where T is an HttpResponseMessage. Task<HttpResponseMessage> httpRMTask = client.GetAsync(currentURI); // Await httpRMTask evaluates to an HttpResponseMessage object. HttpResponseMessage httpRM = await httpRMTask; // The following line can replace the previous two assignment statements . //HttpResponseMessage httpRM = await client.GetAsync(currentURI); // Throw an exception if the HttpResponseMessage contains an error code. httpRM.EnsureSuccessStatusCode(); // Use ReadAsByteArray to access the content of the resource as a byte array. return httpRM.Content.ReadAsByteArray(); }
9.
10.
11.
12.
13. public void AsyncIntroSerialBefore() { var client = new WebClient(); client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_1; client.DownloadStringAsync(new Uri("http://www.weather.gov")); } void AsyncIntroSerialBefore_DownloadStringCompleted_1(object sender, DownloadStringCompletedEventArgs e) { WriteLinePageTitle(e.Result); var client = new WebClient(); client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_2; client.DownloadStringAsync(new Uri("http://www.weather.gov/climate/")); } void AsyncIntroSerialBefore_DownloadStringCompleted_2(object sender, DownloadStringCompletedEventArgs e) { WriteLinePageTitle(e.Result); var client = new WebClient(); client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_3; client.DownloadStringAsync(new Uri("http://www.weather.gov/rss/")); } void AsyncIntroSerialBefore_DownloadStringCompleted_3(object sender, DownloadStringCompletedEventArgs e) { WriteLinePageTitle(e.Result); } C# 4.0
14. public async void AsyncIntroSerial() { var client = new WebClient(); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("http://www.weather.gov"))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("http://www.weather.gov/climate/"))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("http://www.weather.gov/rss/"))); } Async