C# 5: Deep Drive into
Asynchronous Programming

           By- Praveen Kumar Prajapati
    Blog: praveenprajapati.wordpress.com
Agenda
 What’s asynchrony
 Related Terms and Need of Asynchrony
 Why TPL: The Free Lunch is Over
 C# 4: Task Parallel Library
 C# 4: TPL Demo
 C# 5 : Asynchronous Programming
 C# 5 : Behind the Scene
 C# 5 : Async Demo
 Summery
What’s asynchrony
 What’s asynchrony?
    Greek origin
        a (not)
        syn (together with)
        chronos (time)

    Multiple parties evolving in time independently
        Not being blocked



 Synchronous  Wait for result before returning
    string DownloadString(...);


 Asynchronous  Return now, call back with result
    void DownloadStringAsync(..., Action<string> callback);
Related Concepts
 Multithreading
    Use of multiple threads
 Concurrency
    Order in which multiple tasks execute is not determined
 Parallelism
    True simultaneous execution (e.g. multicore)
Need of Asynchrony
 Increasingly connected applications
    More latency
    More UI responsiveness problems
    More scalability issues


 Asynchronous programming
    Becoming the norm in responsive, scalable apps
    More relevant to Metro Style Apps and Window Phone Apps
    Async-only APIs, e.g., JavaScript and Silverlight
Asynchronous Programming
            Model
                       Hang

   UI Thread




                      UI
                    Messages
                                       DisplayPhotos


DownloadDataAsync

                       ParseResponse
Why TPL :
     The Free Lunch is Over
 A paradigm shift
    Then: Faster clocks
    Now: More cores => End of the Free Lunch



 The Free Lunch is Over
    By Herb Sutter in Feb/Mar 2005


    The Free Lunch Is Over
   -A Fundamental Turn Toward Concurrency in Software


    Why You Don’t Have 10GHz Today
The Free Lunch is Over
Single to Multiple Core
       Transition
C# 4 : Task Parallel Library
 “Applications will increasingly need to be concurrent if
  they want to fully exploit continuing exponential CPU
  throughput gains”


 What would be the optimum number of threads for this
  machine?


 But how to decide the degree of concurrency? What if
  server gets more core in future – Change in underlying
  hardware?
C# 4 : Task Parallel Library
 The TPL scales the degree of concurrency dynamically to
  most efficiently use all the processors that are available.


 In addition, the TPL handles the partitioning of the work,
  the scheduling of threads on the ThreadPool,
  cancellation support, state management, and other low-
  level details.


 By using TPL, you can maximize the performance of your
  code while focusing on the work that your program is
  designed to accomplish.
Thread vs. Task
 Task: A Task is a future or a promise. (Some people use
  those two terms synonymously, some use them differently,
  nobody can agree on a precise definition.)


 Basically, a Task<T> "promises" to return you a T, but not
  right now .


 Thread: A Thread is one of many ways to fulfill that
  promise. But not every Task needs a Thread. If the value
  you are waiting for comes from the file system or a
  database or the network, then there is no need for a
  thread. The Task might just register a callback to receive
  the value when the disk is done seeking.


 TPL Demo
C# 5 : Asynchronous
          Programming
 New Keyword introduces:
    async
    Await


 Asynchronous Methods
    As simple as synchronous code
    Unifies computational, network and I/O asynchrony
    More scalable servers
    More responsive UI
C# 5 : Behind the Scene
public async Task<XElement> GetXmlAsync(string url) {
    var client = new HttpClient();
    var response = await client.GetAsync(url);
    var text = response.Content.ReadAsString();
    return XElement.Parse(text);
}



                   public Task<XElement> GetXmlAsync(string url) {
                       var tcs = new TaskCompletionSource<XElement>();
                       var client = new HttpClient();
                       client.GetAsync(url).ContinueWith(task => {
                           var response = task.Result;
                           var text = response.Content.ReadAsString();
                           tcs.SetResult(XElement.Parse(text));
                       });
                       return tcs.Task;
                   }
C# 5 : Async Demo

 Demo: Use of async and await


 How it reduces efforts and make code better
Some Point to Remember
 For any async block it is important to have at least one
  await, otherwise the whole block will work
  synchronously.
 Any async method should postfix Async (as a rule), so
  your method name should look like MyMethodAsync
  which you put an async keyword before it.
 Exceptions to the convention can be made where an
  event, base class, or interface contract suggests a
  different name.
 Any async method can return void(call and forget), Task
  or Task<T> based on the Result the await method
  sends.
 Everything is managed by a State Machine Workflow by
  the compiler
Summery

 Asynchronous Programming and related terms
 Why it is so relevant in current days
 Free Lunch is Over
 TPL and Task
 New Kew words : async and await
 Rules and recommendation for new features
References
• Visual Studio Asynchronous Programming
   http://msdn.microsoft.com/en-us/vstudio/async.aspx

• Task Parallel Library
   http://msdn.microsoft.com/en-us/library/dd460717.aspx


• The Future of C# and VB @PDC10
    http://player.microsoftpdc.com/Session/1b127a7d-300e-4385-af8e-ac747fee677a

• Fabulous Adventures in Coding
    http://blogs.msdn.com/b/ericlippert

• John Skeet: Coding Blog
    http://msmvps.com/blogs/jon_skeet
Thanks to You All
Let us grow together
            Keep in touch:
  Blog: praveenprajapati.wordpress.com

C# 5 deep drive into asynchronous programming

  • 1.
    C# 5: DeepDrive into Asynchronous Programming By- Praveen Kumar Prajapati Blog: praveenprajapati.wordpress.com
  • 2.
    Agenda  What’s asynchrony Related Terms and Need of Asynchrony  Why TPL: The Free Lunch is Over  C# 4: Task Parallel Library  C# 4: TPL Demo  C# 5 : Asynchronous Programming  C# 5 : Behind the Scene  C# 5 : Async Demo  Summery
  • 3.
    What’s asynchrony  What’sasynchrony?  Greek origin  a (not)  syn (together with)  chronos (time)  Multiple parties evolving in time independently  Not being blocked  Synchronous  Wait for result before returning  string DownloadString(...);  Asynchronous  Return now, call back with result  void DownloadStringAsync(..., Action<string> callback);
  • 4.
    Related Concepts  Multithreading  Use of multiple threads  Concurrency  Order in which multiple tasks execute is not determined  Parallelism  True simultaneous execution (e.g. multicore)
  • 5.
    Need of Asynchrony Increasingly connected applications  More latency  More UI responsiveness problems  More scalability issues  Asynchronous programming  Becoming the norm in responsive, scalable apps  More relevant to Metro Style Apps and Window Phone Apps  Async-only APIs, e.g., JavaScript and Silverlight
  • 6.
    Asynchronous Programming Model Hang UI Thread UI Messages DisplayPhotos DownloadDataAsync ParseResponse
  • 7.
    Why TPL : The Free Lunch is Over  A paradigm shift  Then: Faster clocks  Now: More cores => End of the Free Lunch  The Free Lunch is Over  By Herb Sutter in Feb/Mar 2005  The Free Lunch Is Over -A Fundamental Turn Toward Concurrency in Software  Why You Don’t Have 10GHz Today
  • 8.
  • 9.
    Single to MultipleCore Transition
  • 10.
    C# 4 :Task Parallel Library  “Applications will increasingly need to be concurrent if they want to fully exploit continuing exponential CPU throughput gains”  What would be the optimum number of threads for this machine?  But how to decide the degree of concurrency? What if server gets more core in future – Change in underlying hardware?
  • 11.
    C# 4 :Task Parallel Library  The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available.  In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low- level details.  By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.
  • 12.
    Thread vs. Task Task: A Task is a future or a promise. (Some people use those two terms synonymously, some use them differently, nobody can agree on a precise definition.)  Basically, a Task<T> "promises" to return you a T, but not right now .  Thread: A Thread is one of many ways to fulfill that promise. But not every Task needs a Thread. If the value you are waiting for comes from the file system or a database or the network, then there is no need for a thread. The Task might just register a callback to receive the value when the disk is done seeking.  TPL Demo
  • 13.
    C# 5 :Asynchronous Programming  New Keyword introduces:  async  Await  Asynchronous Methods  As simple as synchronous code  Unifies computational, network and I/O asynchrony  More scalable servers  More responsive UI
  • 14.
    C# 5 :Behind the Scene public async Task<XElement> GetXmlAsync(string url) { var client = new HttpClient(); var response = await client.GetAsync(url); var text = response.Content.ReadAsString(); return XElement.Parse(text); } public Task<XElement> GetXmlAsync(string url) { var tcs = new TaskCompletionSource<XElement>(); var client = new HttpClient(); client.GetAsync(url).ContinueWith(task => { var response = task.Result; var text = response.Content.ReadAsString(); tcs.SetResult(XElement.Parse(text)); }); return tcs.Task; }
  • 15.
    C# 5 :Async Demo  Demo: Use of async and await  How it reduces efforts and make code better
  • 16.
    Some Point toRemember  For any async block it is important to have at least one await, otherwise the whole block will work synchronously.  Any async method should postfix Async (as a rule), so your method name should look like MyMethodAsync which you put an async keyword before it.  Exceptions to the convention can be made where an event, base class, or interface contract suggests a different name.  Any async method can return void(call and forget), Task or Task<T> based on the Result the await method sends.  Everything is managed by a State Machine Workflow by the compiler
  • 17.
    Summery  Asynchronous Programmingand related terms  Why it is so relevant in current days  Free Lunch is Over  TPL and Task  New Kew words : async and await  Rules and recommendation for new features
  • 18.
    References • Visual StudioAsynchronous Programming http://msdn.microsoft.com/en-us/vstudio/async.aspx • Task Parallel Library http://msdn.microsoft.com/en-us/library/dd460717.aspx • The Future of C# and VB @PDC10 http://player.microsoftpdc.com/Session/1b127a7d-300e-4385-af8e-ac747fee677a • Fabulous Adventures in Coding http://blogs.msdn.com/b/ericlippert • John Skeet: Coding Blog http://msmvps.com/blogs/jon_skeet
  • 19.
    Thanks to YouAll Let us grow together Keep in touch: Blog: praveenprajapati.wordpress.com