SlideShare a Scribd company logo
1 of 15
Asynchronous Programming
in ASP.NET
Chris Dufour, ASP .NET MVP
Software Architect, Compuware
   Follow me @chrduf
   http://www.linkedin.com/in/cdufour
Agenda
•   ASP .NET page lifecycle
•   Load test synchronous application
•   History of Async support in ASP.NET
•   TAP (Task-based Asynchronous Pattern)
•   Asynchronize the application
•   Load test asynchronous application
ASP.NET Page Lifecycle
demo
Load Test Synchronous Page
Sync vs. Async
• Synchronous call
   • Caller WAITS for method to complete
   • “Blocking”
   • Easy to program/understand
• Asynchronous call
   • Method returns immediately to caller and executes callback
     (continuation) when complete
   • “Non-blocking”
   • Run several methods concurrently
   • Scalability
   • Harder to program
Asynchronous History
.NET 1.1 - APM (Asynchronous Programming Model)

• Call BeginXxx to start doing work
    • Returns IAsyncResult which reflects status
    • Doesn’t always run async
    • Problems with thread affinity
• Call EndXxx to get the actual result value
• No built-in support for async pages in ASP .NET
Asynchronous History
.NET 2.0 - EAP (Event-Based Asynchronous Pattern)

• Call XxxAsync to start work
     • Often no way to get status while in-flight
     • Problems with thread affinity
• Subscribe to XxxCompleted event to get result
• Introduces support for Async pages in ASP.NET
ASP.NET Asynchronous Page Lifecycle
Asynchronous Data Binding
public partial class AsyncDataBind : System.Web.UI.Page
{                                                                                        void EndAsyncOperation(IAsyncResult ar)
    private SqlConnection _connection;                                                   {
    private SqlCommand _command;
                                                                                             _reader = _command.EndExecuteReader(ar);
    private SqlDataReader _reader;
                                                                                         }
   protected void Page_Load(object sender, EventArgs e)
   {                                                                                     protected void Page_PreRenderComplete(object sender, EventArgs e)
       if (!IsPostBack)                                                                  {
       {                                                                                     Output.DataSource = _reader;
           // Hook PreRenderComplete event for data binding                                  Output.DataBind();
           this.PreRenderComplete += new EventHandler(Page_PreRenderComplete);           }
           // Register async methods
           AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation),
                                                                                         public override void Dispose()
               new EndEventHandler(EndAsyncOperation)                                    {
           );                                                                                if (_connection != null) _connection.Close();
       }                                                                                     base.Dispose();
   }                                                                                     }
   IAsyncResult BeginAsyncOperation (object sender, EventArgs e,                     }
       AsyncCallback cb, object state)
   {
       string connect = WebConfigurationManager.ConnectionStrings
           ["PubsConnectionString"].ConnectionString;
       _connection = new SqlConnection(connect);
       _connection.Open();
       _command = new SqlCommand(
           "SELECT title_id, title, price FROM titles", _connection);
       return _command.BeginExecuteReader (cb, state);
   }
Asynchronous History
.NET 4.0 – TPL (Task Parallel Library)

• Call XxxAsync to start work
     • Returns Task (or Task<T>) to reflect in-flight status
     • Problems with thread affinity
• No second method or event

Task<int> t = SomethingAsync(…);
//do work, checking t.Status
int r = t.Result
Asynchronous History
.NET 4.5 – TAP (Task-Based Asynchronous Pattern)

• Works on top of TPL
• Introduces 2 new contextual key words
     • Async marks a method as asynchronous
     • Await yields control while waiting on a task to complete
• Lets us write sequential code which is not necessarily
  synchronous
• Takes care of sticky threading & performance issues
  related to Task<T>
TAP
protected void Page_Load(...)
{
    int r = DoWork();
}

private int DoWork()
{
    DoSomeWork;
    return 1;
}
TAP
protected void Page_Load(...)   Protected async void Page_Load(...)
{                               {
    int r = DoWork();               int r = await DoWorkAsync();
}                               }

private int DoWork()            Private async Task<int> DoWorkAsync()
{                               {
    DoSomeWork;                     await Task.Run(DoSomeWork);
    return 1;                       return 1;
}                               }
demo
Asynchronize the Application
Thank You

More Related Content

What's hot

Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETAliaksandr Famin
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
Reduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin CoroutinesReduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin CoroutinesLINE Corporation
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
Efficiently exposing services on Kubernetes (part 2)
Efficiently exposing services on Kubernetes (part 2)Efficiently exposing services on Kubernetes (part 2)
Efficiently exposing services on Kubernetes (part 2)Ahmad Iqbal Ali
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2MongoDB
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 

What's hot (20)

Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NETEvolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Reduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin CoroutinesReduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin Coroutines
 
Async await
Async awaitAsync await
Async await
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
AMC Minor Technical Issues
AMC Minor Technical IssuesAMC Minor Technical Issues
AMC Minor Technical Issues
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
Async/Await
Async/AwaitAsync/Await
Async/Await
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Efficiently exposing services on Kubernetes (part 2)
Efficiently exposing services on Kubernetes (part 2)Efficiently exposing services on Kubernetes (part 2)
Efficiently exposing services on Kubernetes (part 2)
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
NodeJs
NodeJsNodeJs
NodeJs
 
rx-java-presentation
rx-java-presentationrx-java-presentation
rx-java-presentation
 
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 

Similar to Asynchronous Programming in ASP.NET

Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programováníPeckaDesign.cz
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Paco de la Cruz
 
Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverMongoDB
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍명신 김
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Paco de la Cruz
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best PracticesLluis Franco
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackNelson Glauber Leal
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Device Simulator with Akka
Device Simulator with AkkaDevice Simulator with Akka
Device Simulator with AkkaMax Huang
 
Windows 8 Development
Windows 8 Development Windows 8 Development
Windows 8 Development Eyal Vardi
 

Similar to Asynchronous Programming in ASP.NET (20)

Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET Driver
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Winform
WinformWinform
Winform
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Device Simulator with Akka
Device Simulator with AkkaDevice Simulator with Akka
Device Simulator with Akka
 
Windows 8 Development
Windows 8 Development Windows 8 Development
Windows 8 Development
 

More from Chris Dufour

Introduction to ASP.NET 5
Introduction to ASP.NET 5Introduction to ASP.NET 5
Introduction to ASP.NET 5Chris Dufour
 
Developing Windows 10 Hosted Web Apps
Developing Windows 10 Hosted Web AppsDeveloping Windows 10 Hosted Web Apps
Developing Windows 10 Hosted Web AppsChris Dufour
 
Developing windows 10 universal apps
Developing windows 10 universal appsDeveloping windows 10 universal apps
Developing windows 10 universal appsChris Dufour
 
DevCamp - What can the cloud do for me
DevCamp - What can the cloud do for meDevCamp - What can the cloud do for me
DevCamp - What can the cloud do for meChris Dufour
 
Microsoft Azure Platform-as-a-Service (PaaS)
Microsoft Azure Platform-as-a-Service (PaaS)Microsoft Azure Platform-as-a-Service (PaaS)
Microsoft Azure Platform-as-a-Service (PaaS)Chris Dufour
 
Migrate an Existing Application to Microsoft Azure
Migrate an Existing Application to Microsoft AzureMigrate an Existing Application to Microsoft Azure
Migrate an Existing Application to Microsoft AzureChris Dufour
 
Whats new for developers in Visual Studio 2013
Whats new for developers in Visual Studio 2013Whats new for developers in Visual Studio 2013
Whats new for developers in Visual Studio 2013Chris Dufour
 
Windows Azure Active Directory: Identity Management in the Cloud
Windows Azure Active Directory: Identity Management in the CloudWindows Azure Active Directory: Identity Management in the Cloud
Windows Azure Active Directory: Identity Management in the CloudChris Dufour
 
Introduction to CSLA
Introduction to CSLAIntroduction to CSLA
Introduction to CSLAChris Dufour
 
Implementing OData: Create a UG Event Feed
Implementing OData: Create a UG Event FeedImplementing OData: Create a UG Event Feed
Implementing OData: Create a UG Event FeedChris Dufour
 
Scale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App FabricScale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App FabricChris Dufour
 

More from Chris Dufour (11)

Introduction to ASP.NET 5
Introduction to ASP.NET 5Introduction to ASP.NET 5
Introduction to ASP.NET 5
 
Developing Windows 10 Hosted Web Apps
Developing Windows 10 Hosted Web AppsDeveloping Windows 10 Hosted Web Apps
Developing Windows 10 Hosted Web Apps
 
Developing windows 10 universal apps
Developing windows 10 universal appsDeveloping windows 10 universal apps
Developing windows 10 universal apps
 
DevCamp - What can the cloud do for me
DevCamp - What can the cloud do for meDevCamp - What can the cloud do for me
DevCamp - What can the cloud do for me
 
Microsoft Azure Platform-as-a-Service (PaaS)
Microsoft Azure Platform-as-a-Service (PaaS)Microsoft Azure Platform-as-a-Service (PaaS)
Microsoft Azure Platform-as-a-Service (PaaS)
 
Migrate an Existing Application to Microsoft Azure
Migrate an Existing Application to Microsoft AzureMigrate an Existing Application to Microsoft Azure
Migrate an Existing Application to Microsoft Azure
 
Whats new for developers in Visual Studio 2013
Whats new for developers in Visual Studio 2013Whats new for developers in Visual Studio 2013
Whats new for developers in Visual Studio 2013
 
Windows Azure Active Directory: Identity Management in the Cloud
Windows Azure Active Directory: Identity Management in the CloudWindows Azure Active Directory: Identity Management in the Cloud
Windows Azure Active Directory: Identity Management in the Cloud
 
Introduction to CSLA
Introduction to CSLAIntroduction to CSLA
Introduction to CSLA
 
Implementing OData: Create a UG Event Feed
Implementing OData: Create a UG Event FeedImplementing OData: Create a UG Event Feed
Implementing OData: Create a UG Event Feed
 
Scale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App FabricScale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App Fabric
 

Recently uploaded

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 

Recently uploaded (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

Asynchronous Programming in ASP.NET

  • 1. Asynchronous Programming in ASP.NET Chris Dufour, ASP .NET MVP Software Architect, Compuware Follow me @chrduf http://www.linkedin.com/in/cdufour
  • 2. Agenda • ASP .NET page lifecycle • Load test synchronous application • History of Async support in ASP.NET • TAP (Task-based Asynchronous Pattern) • Asynchronize the application • Load test asynchronous application
  • 5. Sync vs. Async • Synchronous call • Caller WAITS for method to complete • “Blocking” • Easy to program/understand • Asynchronous call • Method returns immediately to caller and executes callback (continuation) when complete • “Non-blocking” • Run several methods concurrently • Scalability • Harder to program
  • 6. Asynchronous History .NET 1.1 - APM (Asynchronous Programming Model) • Call BeginXxx to start doing work • Returns IAsyncResult which reflects status • Doesn’t always run async • Problems with thread affinity • Call EndXxx to get the actual result value • No built-in support for async pages in ASP .NET
  • 7. Asynchronous History .NET 2.0 - EAP (Event-Based Asynchronous Pattern) • Call XxxAsync to start work • Often no way to get status while in-flight • Problems with thread affinity • Subscribe to XxxCompleted event to get result • Introduces support for Async pages in ASP.NET
  • 9. Asynchronous Data Binding public partial class AsyncDataBind : System.Web.UI.Page { void EndAsyncOperation(IAsyncResult ar) private SqlConnection _connection; { private SqlCommand _command; _reader = _command.EndExecuteReader(ar); private SqlDataReader _reader; } protected void Page_Load(object sender, EventArgs e) { protected void Page_PreRenderComplete(object sender, EventArgs e) if (!IsPostBack) { { Output.DataSource = _reader; // Hook PreRenderComplete event for data binding Output.DataBind(); this.PreRenderComplete += new EventHandler(Page_PreRenderComplete); } // Register async methods AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), public override void Dispose() new EndEventHandler(EndAsyncOperation) { ); if (_connection != null) _connection.Close(); } base.Dispose(); } } IAsyncResult BeginAsyncOperation (object sender, EventArgs e, } AsyncCallback cb, object state) { string connect = WebConfigurationManager.ConnectionStrings ["PubsConnectionString"].ConnectionString; _connection = new SqlConnection(connect); _connection.Open(); _command = new SqlCommand( "SELECT title_id, title, price FROM titles", _connection); return _command.BeginExecuteReader (cb, state); }
  • 10. Asynchronous History .NET 4.0 – TPL (Task Parallel Library) • Call XxxAsync to start work • Returns Task (or Task<T>) to reflect in-flight status • Problems with thread affinity • No second method or event Task<int> t = SomethingAsync(…); //do work, checking t.Status int r = t.Result
  • 11. Asynchronous History .NET 4.5 – TAP (Task-Based Asynchronous Pattern) • Works on top of TPL • Introduces 2 new contextual key words • Async marks a method as asynchronous • Await yields control while waiting on a task to complete • Lets us write sequential code which is not necessarily synchronous • Takes care of sticky threading & performance issues related to Task<T>
  • 12. TAP protected void Page_Load(...) { int r = DoWork(); } private int DoWork() { DoSomeWork; return 1; }
  • 13. TAP protected void Page_Load(...) Protected async void Page_Load(...) { { int r = DoWork(); int r = await DoWorkAsync(); } } private int DoWork() Private async Task<int> DoWorkAsync() { { DoSomeWork; await Task.Run(DoSomeWork); return 1; return 1; } }