SlideShare a Scribd company logo
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
Ad

Recommended

Async in .NET
Async in .NET
RTigger
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
Binu Bhasuran
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programming
Praveen Prajapati
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutes
Paulo Morgado
 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
Mindfire Solutions
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
Spiffy
 
Async and Await on the Server
Async and Await on the Server
Doug Jones
 
End to-end async and await
End to-end async and await
vfabro
 
Async Programming in C# 5
Async Programming in C# 5
Pratik Khasnabis
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
Aliaksandr Famin
 
Sync with async
Sync with async
prabathsl
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
Async Await for Mobile Apps
Async Await for Mobile Apps
Craig Dunn
 
Task parallel library presentation
Task parallel library presentation
ahmed sayed
 
Reduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin Coroutines
LINE Corporation
 
Async await
Async await
Jeff Hart
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
Tomasz Kowalczewski
 
AMC Minor Technical Issues
AMC Minor Technical Issues
Apache Traffic Server
 
Introduction to Reactive Java
Introduction to Reactive Java
Tomasz Kowalczewski
 
Async/Await
Async/Await
Jeff Hart
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
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 js
Thomas Roch
 
NodeJs
NodeJs
Orkhan Muradov
 
rx-java-presentation
rx-java-presentation
Mateusz Bukowicz
 
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB
 
Asynchronous development in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Async Best Practices
Async Best Practices
Lluis Franco
 
History of asynchronous in .NET
History of asynchronous in .NET
Marcin Tyborowski
 

More Related Content

What's hot (20)

Async Programming in C# 5
Async Programming in C# 5
Pratik Khasnabis
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
Aliaksandr Famin
 
Sync with async
Sync with async
prabathsl
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
Async Await for Mobile Apps
Async Await for Mobile Apps
Craig Dunn
 
Task parallel library presentation
Task parallel library presentation
ahmed sayed
 
Reduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin Coroutines
LINE Corporation
 
Async await
Async await
Jeff Hart
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
Tomasz Kowalczewski
 
AMC Minor Technical Issues
AMC Minor Technical Issues
Apache Traffic Server
 
Introduction to Reactive Java
Introduction to Reactive Java
Tomasz Kowalczewski
 
Async/Await
Async/Await
Jeff Hart
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
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 js
Thomas Roch
 
NodeJs
NodeJs
Orkhan Muradov
 
rx-java-presentation
rx-java-presentation
Mateusz Bukowicz
 
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB
 
Asynchronous development in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
Evolution of asynchrony in (ASP).NET
Evolution of asynchrony in (ASP).NET
Aliaksandr Famin
 
Sync with async
Sync with async
prabathsl
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
Async Await for Mobile Apps
Async Await for Mobile Apps
Craig Dunn
 
Task parallel library presentation
Task parallel library presentation
ahmed sayed
 
Reduce dependency on Rx with Kotlin Coroutines
Reduce dependency on Rx with Kotlin Coroutines
LINE Corporation
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
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 js
Thomas Roch
 
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB World 2016: Implementing Async Networking in MongoDB 3.2
MongoDB
 
Asynchronous development in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 

Similar to Asynchronous Programming in ASP.NET (20)

Async Best Practices
Async Best Practices
Lluis Franco
 
History of asynchronous in .NET
History of asynchronous in .NET
Marcin Tyborowski
 
Asynchronyin net
Asynchronyin net
Soacat Blogspot
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
Alex Thissen
 
What's New In C# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOut
Paulo Morgado
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
jeffz
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
Rainer Stropek
 
MVVM Applied: From Silverlight to Windows Phone to Windows 8
MVVM Applied: From Silverlight to Windows Phone to Windows 8
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
M S Ajax Client Life Cycle Events
M S Ajax Client Life Cycle Events
51 lecture
 
Paulo morgado what's new in c# 5.0
Paulo morgado what's new in c# 5.0
iseltech
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4
Simone Chiaretta
 
Asynchronous programming
Asynchronous programming
Filip Ekberg
 
What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13
Paulo Morgado
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#
Rainer Stropek
 
Hidden Facts of .NET Language Gems
Hidden Facts of .NET Language Gems
Abhishek Sur
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
09 gui 13
09 gui 13
Niit Care
 
Asynchronous in dot net4
Asynchronous in dot net4
Wei Sun
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
oazabir
 
Async Best Practices
Async Best Practices
Lluis Franco
 
History of asynchronous in .NET
History of asynchronous in .NET
Marcin Tyborowski
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
Alex Thissen
 
What's New In C# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOut
Paulo Morgado
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
jeffz
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
Rainer Stropek
 
M S Ajax Client Life Cycle Events
M S Ajax Client Life Cycle Events
51 lecture
 
Paulo morgado what's new in c# 5.0
Paulo morgado what's new in c# 5.0
iseltech
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4
Simone Chiaretta
 
Asynchronous programming
Asynchronous programming
Filip Ekberg
 
What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13
Paulo Morgado
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#
Rainer Stropek
 
Hidden Facts of .NET Language Gems
Hidden Facts of .NET Language Gems
Abhishek Sur
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Asynchronous in dot net4
Asynchronous in dot net4
Wei Sun
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
oazabir
 
Ad

More from Chris Dufour (11)

Introduction to ASP.NET 5
Introduction to ASP.NET 5
Chris Dufour
 
Developing Windows 10 Hosted Web Apps
Developing Windows 10 Hosted Web Apps
Chris Dufour
 
Developing windows 10 universal apps
Developing windows 10 universal apps
Chris Dufour
 
DevCamp - What can the cloud do for me
DevCamp - What can the cloud do for me
Chris Dufour
 
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 Azure
Chris Dufour
 
Whats new for developers in Visual Studio 2013
Whats new for developers in Visual Studio 2013
Chris Dufour
 
Windows Azure Active Directory: Identity Management in the Cloud
Windows Azure Active Directory: Identity Management in the Cloud
Chris Dufour
 
Introduction to CSLA
Introduction to CSLA
Chris Dufour
 
Implementing OData: Create a UG Event Feed
Implementing OData: Create a UG Event Feed
Chris Dufour
 
Scale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App Fabric
Chris Dufour
 
Introduction to ASP.NET 5
Introduction to ASP.NET 5
Chris Dufour
 
Developing Windows 10 Hosted Web Apps
Developing Windows 10 Hosted Web Apps
Chris Dufour
 
Developing windows 10 universal apps
Developing windows 10 universal apps
Chris Dufour
 
DevCamp - What can the cloud do for me
DevCamp - What can the cloud do for me
Chris Dufour
 
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 Azure
Chris Dufour
 
Whats new for developers in Visual Studio 2013
Whats new for developers in Visual Studio 2013
Chris Dufour
 
Windows Azure Active Directory: Identity Management in the Cloud
Windows Azure Active Directory: Identity Management in the Cloud
Chris Dufour
 
Introduction to CSLA
Introduction to CSLA
Chris Dufour
 
Implementing OData: Create a UG Event Feed
Implementing OData: Create a UG Event Feed
Chris Dufour
 
Scale Your Data Tier With Windows Server App Fabric
Scale Your Data Tier With Windows Server App Fabric
Chris Dufour
 
Ad

Recently uploaded (20)

The Future of AI Agent Development Trends to Watch.pptx
The Future of AI Agent Development Trends to Watch.pptx
Lisa ward
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
The Future of Data, AI, and AR: Innovation Inspired by You.pdf
The Future of Data, AI, and AR: Innovation Inspired by You.pdf
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
The Future of AI Agent Development Trends to Watch.pptx
The Future of AI Agent Development Trends to Watch.pptx
Lisa ward
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
The Future of Data, AI, and AR: Innovation Inspired by You.pdf
The Future of Data, AI, and AR: Innovation Inspired by You.pdf
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 

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; } }