SlideShare une entreprise Scribd logo
1  sur  19
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

Contenu connexe

Tendances

Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush Sharma
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014Thomas Lockney
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexAkshay Varu
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with RxjavaChristophe Marchal
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaKasun Indrasiri
 
Infrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using PrometheusInfrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using PrometheusMarco Pas
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxAndrzej Sitek
 
Using Grails to power your electric car
Using Grails to power your electric carUsing Grails to power your electric car
Using Grails to power your electric carMarco Pas
 

Tendances (20)

Async/Await
Async/AwaitAsync/Await
Async/Await
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Async await
Async awaitAsync await
Async await
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
 
AMC Minor Technical Issues
AMC Minor Technical IssuesAMC Minor Technical Issues
AMC Minor Technical Issues
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Infrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using PrometheusInfrastructure & System Monitoring using Prometheus
Infrastructure & System Monitoring using Prometheus
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Using Grails to power your electric car
Using Grails to power your electric carUsing Grails to power your electric car
Using Grails to power your electric car
 

En vedette

Asynchronous Programming with C#
Asynchronous Programming with C#Asynchronous Programming with C#
Asynchronous Programming with C#Muhammed Tahiroglu
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharpDeivaa
 
Quy tắc thiết kế giao diện và viết code C#
Quy tắc thiết kế giao diện và viết code C#Quy tắc thiết kế giao diện và viết code C#
Quy tắc thiết kế giao diện và viết code C#An Nguyen
 
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...MasterCode.vn
 
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPTBÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPTMasterCode.vn
 
Threading in c#
Threading in c#Threading in c#
Threading in c#gohsiauken
 

En vedette (7)

Asynchronous Programming with C#
Asynchronous Programming with C#Asynchronous Programming with C#
Asynchronous Programming with C#
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Quy tắc thiết kế giao diện và viết code C#
Quy tắc thiết kế giao diện và viết code C#Quy tắc thiết kế giao diện và viết code C#
Quy tắc thiết kế giao diện và viết code C#
 
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
 
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPTBÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
BÀI 2: Thiết kế FORM và xử lý sự kiện - Giáo trình FPT
 
Threading in c#
Threading in c#Threading in c#
Threading in c#
 

Similaire à C# 5 deep drive into asynchronous programming

Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET WayBishnu Rawal
 
Natural Laws of Software Performance
Natural Laws of Software PerformanceNatural Laws of Software Performance
Natural Laws of Software PerformanceGibraltar Software
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue10n Software, LLC
 
DevOps Fest 2020. immutable infrastructure as code. True story.
DevOps Fest 2020. immutable infrastructure as code. True story.DevOps Fest 2020. immutable infrastructure as code. True story.
DevOps Fest 2020. immutable infrastructure as code. True story.Vlad Fedosov
 
5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptx5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptxMohamedBilal73
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5Malam Team
 
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect ToolboxWebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect ToolboxWebCamp
 
Building and deploying LLM applications with Apache Airflow
Building and deploying LLM applications with Apache AirflowBuilding and deploying LLM applications with Apache Airflow
Building and deploying LLM applications with Apache AirflowKaxil Naik
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NETPierre-Luc Maheu
 
C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programmingUmeshwaran V
 
Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event LoopTorontoNodeJS
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
 
High Performance Coding2.pptx
High Performance Coding2.pptxHigh Performance Coding2.pptx
High Performance Coding2.pptxShymmaaQadoom1
 
MERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingMERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingOlivier NAVARRE
 
Splunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the messageSplunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the messageDamien Dallimore
 
Async await in C++
Async await in C++Async await in C++
Async await in C++cppfrug
 

Similaire à C# 5 deep drive into asynchronous programming (20)

Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
 
Natural Laws of Software Performance
Natural Laws of Software PerformanceNatural Laws of Software Performance
Natural Laws of Software Performance
 
Slideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You QueueSlideshare - Magento Imagine - Do You Queue
Slideshare - Magento Imagine - Do You Queue
 
DevOps Fest 2020. immutable infrastructure as code. True story.
DevOps Fest 2020. immutable infrastructure as code. True story.DevOps Fest 2020. immutable infrastructure as code. True story.
DevOps Fest 2020. immutable infrastructure as code. True story.
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptx5.7 Parallel Processing - Reactive Programming.pdf.pptx
5.7 Parallel Processing - Reactive Programming.pdf.pptx
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5
 
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect ToolboxWebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
 
Concurrency in c#
Concurrency in c#Concurrency in c#
Concurrency in c#
 
Building and deploying LLM applications with Apache Airflow
Building and deploying LLM applications with Apache AirflowBuilding and deploying LLM applications with Apache Airflow
Building and deploying LLM applications with Apache Airflow
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
 
C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programming
 
Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event Loop
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
High Performance Coding2.pptx
High Performance Coding2.pptxHigh Performance Coding2.pptx
High Performance Coding2.pptx
 
MERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingMERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel Programming
 
Splunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the messageSplunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the message
 
Proposal
ProposalProposal
Proposal
 
Async await in C++
Async await in C++Async await in C++
Async await in C++
 

Dernier

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Dernier (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

C# 5 deep drive into asynchronous programming

  • 1. C# 5: Deep Drive 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’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);
  • 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. The Free Lunch is Over
  • 9. Single to Multiple Core 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 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
  • 17. 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
  • 18. 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
  • 19. Thanks to You All Let us grow together Keep in touch: Blog: praveenprajapati.wordpress.com