Asynchronous in dot net4


Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Asynchronous in dot net4

  1. 1. Asynchronous in DotNet4.5
  2. 2. <ul><li> </li></ul><ul><li> </li></ul>
  3. 3. Task & Task<T> <ul><li>var t = Task.Factory.StartNew(() => DoAction()); </li></ul><ul><li>The Task. ContinueWith method and Task<TResult>.ContinueWith method let you specify a task to be started when the antecedent task finishes. </li></ul>
  4. 4. Action<object> action = (object obj) => { Console.WriteLine(&quot;Task={0}, obj={1}, Thread={2}&quot;, Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId); }; // Construct an unstarted task Task t1 = new Task(action, &quot;alpha&quot;); // Cosntruct a started task Task t2 = Task.Factory.StartNew(action, &quot;beta&quot;); // Block the main thread to demonstate that t2 is executing t2.Wait(); // Launch t1 t1.Start(); Console.WriteLine(&quot;t1 has been launched. (Main Thread={0})&quot;, 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, &quot;gamma&quot;); // 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. 5. async await <ul><li>The async modifier indicates that the method,  lambda expression , or  anonymous method  that it modifies is asynchronous. Such methods are referred to as  async methods . </li></ul><ul><li>An async method provides a convenient way to do potentially long-running work without blocking the caller's thread. The caller of an async method can resume its work without waiting for the async method to finish. </li></ul><ul><li>The following example shows the structure of an async method. By convention, async method names end in &quot;Async.“ </li></ul><ul><li>Typically, a method modified by the async keyword contains at least one  await  expression or statement. The method runs synchronously until it reaches the first await expression, at which point it is suspended until the awaited task is complete. In the meantime, control is returned to the caller of the method. If the method does not contain an await expression or statement, then it executes synchronously. A compiler warning alerts you to any async methods that do not contain await. </li></ul>
  6. 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. 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 += &quot;rnControl returned to button1_Click.rn&quot;; } // 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 += &quot;rnControl returned to button1_Click.rn&quot;; }
  8. 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. 9. Task Parallelism <ul><li>The Task Parallel Library (TPL), as its name implies, is based on the concept of the task. The term task parallelism refers to one or more independent tasks running concurrently. A task represents an asynchronous operation, and in some ways it resembles the creation of a new thread or ThreadPool work item, but at a higher level of abstraction. Tasks provide two primary benefits: </li></ul><ul><li>More efficient and more scalable use of system resources. </li></ul><ul><li>Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing. </li></ul><ul><li>More programmatic control than is possible with a thread or work item. </li></ul><ul><li>Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more. </li></ul><ul><li>For both of these reasons, in the .NET Framework 4, tasks are the preferred API for writing multi-threaded, asynchronous, and parallel code. </li></ul>
  10. 10. <ul><li>The following changes are all that is required to convert from a synchronous to an asynchronous method. </li></ul><ul><li>In the method signature, make the following three changes: </li></ul><ul><ul><li>Mark the method with the Async or async modifier. </li></ul></ul><ul><ul><li>Change the return value from Byte() or byte[] to Task(Of Byte()) or Task<byte[]>. </li></ul></ul><ul><ul><li>By convention, add the suffix &quot;Async&quot; to the method name. </li></ul></ul><ul><li>In the body of the method, make the following two changes: </li></ul><ul><ul><li>Change the method that is called from the synchronous Get method to the asynchronous GetAsync method. </li></ul></ul><ul><ul><li>Apply the Await or await operator to the result of the method call. </li></ul></ul><ul><li>That's it. Those few steps complete the conversion. </li></ul>
  11. 11. Async Samples <ul><li> </li></ul>
  12. 12. <ul><li>Performs a series of web requests in sequence using await. The next request will not be issued until the previous request completes. </li></ul>
  13. 13. public void AsyncIntroSerialBefore() { var client = new WebClient(); client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_1; client.DownloadStringAsync(new Uri(&quot;;)); } void AsyncIntroSerialBefore_DownloadStringCompleted_1(object sender, DownloadStringCompletedEventArgs e) { WriteLinePageTitle(e.Result); var client = new WebClient(); client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_2; client.DownloadStringAsync(new Uri(&quot;;)); } void AsyncIntroSerialBefore_DownloadStringCompleted_2(object sender, DownloadStringCompletedEventArgs e) { WriteLinePageTitle(e.Result); var client = new WebClient(); client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_3; client.DownloadStringAsync(new Uri(&quot;;)); } void AsyncIntroSerialBefore_DownloadStringCompleted_3(object sender, DownloadStringCompletedEventArgs e) { WriteLinePageTitle(e.Result); } C# 4.0
  14. 14. public async void AsyncIntroSerial() { var client = new WebClient(); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri(&quot;;))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri(&quot;;))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri(&quot;;))); } Async
  15. 15. Resources