Asynchronous in dot net4
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Asynchronous in dot net4

on

  • 1,523 views

 

Statistics

Views

Total Views
1,523
Views on SlideShare
1,523
Embed Views
0

Actions

Likes
0
Downloads
19
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Asynchronous in dot net4 Presentation Transcript

  • 1. Asynchronous in DotNet4.5
  • 2.
    • http://msdn.microsoft.com/en-US/vstudio/async
    • http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=9983
  • 3. Task & Task<T>
    • var t = Task.Factory.StartNew(() => DoAction());
    • The Task. ContinueWith method and Task<TResult>.ContinueWith method let you specify a task to be started when the antecedent task finishes.
    http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=VS.110).aspx
  • 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. async await
    • 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 .
    • 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.
    • The following example shows the structure of an async method. By convention, async method names end in &quot;Async.“
    • 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.
    http://msdn.microsoft.com/en-us/library/hh156513(v=VS.110).aspx
  • 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 += &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. // 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. Task Parallelism http://msdn.microsoft.com/en-us/library/dd537609(v=VS.110).aspx
    • 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:
    • More efficient and more scalable use of system resources.
    • 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.
    • More programmatic control than is possible with a thread or work item.
    • 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.
    • For both of these reasons, in the .NET Framework 4, tasks are the preferred API for writing multi-threaded, asynchronous, and parallel code.
  • 10.
    • The following changes are all that is required to convert from a synchronous to an asynchronous method.
    • In the method signature, make the following three changes:
      • Mark the method with the Async or async modifier.
      • Change the return value from Byte() or byte[] to Task(Of Byte()) or Task<byte[]>.
      • By convention, add the suffix &quot;Async&quot; to the method name.
    • In the body of the method, make the following two changes:
      • Change the method that is called from the synchronous Get method to the asynchronous GetAsync method.
      • Apply the Await or await operator to the result of the method call.
    • That's it. Those few steps complete the conversion.
    http://msdn.microsoft.com/en-us/library/hh191443(v=VS.110).aspx
  • 11. Async Samples
    • http://www.wischik.com/lu/AsyncSilverlight/AsyncSamples.html
  • 12.
    • Performs a series of web requests in sequence using await. The next request will not be issued until the previous request completes.
  • 13. public void AsyncIntroSerialBefore() { var client = new WebClient(); client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_1; client.DownloadStringAsync(new Uri(&quot;http://www.weather.gov&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;http://www.weather.gov/climate/&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;http://www.weather.gov/rss/&quot;)); } 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(&quot;http://www.weather.gov&quot;))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri(&quot;http://www.weather.gov/climate/&quot;))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri(&quot;http://www.weather.gov/rss/&quot;))); } Async
  • 15. Resources http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-829T