SlideShare ist ein Scribd-Unternehmen logo
1 von 43
End-to-End Async and Await
Vince Fabro
Cardinal Solutions
Practice Manager, Enterprise App Dev
@vfabro
Agenda
• What is Async?
• Why bother?
• How does this work?
• Gotchas
• Best Practices & More Details
• Next Steps
Agenda
• What is Async?
• Why bother?
• How does this work?
• Gotchas
• Best Practices & More Details
• Next Steps
What is Async?
• C# 5.0 and .NET 4.5
• async and await keywords
• Asynchronous programming for the
masses!
What is Async?
• Asynchronous == Parallel?
• Asynchronous == Multithreaded?
• Asynchronous == Easy?
Agenda
• What is Async?
• Why bother?
• How does this work?
• Gotchas
• Best Practices & More Details
• Next Steps
Why bother?
• Improve app responsiveness
• Simplify asynchronous programming
 more approachable
Simpler /
More approachable than what?
Asynchrony the good old way
• [… as opposed to the much worse older ways]
• APM and EAP
• APM – Asynchronous Programming Model
– http://msdn.microsoft.com/en-us/library/ms228963%28v=vs.110%29.aspx
– http://msdn.microsoft.com/en-us/magazine/cc163467.aspx
• EAP – Event-based Asynchronous Pattern
– http://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx
Asynchronous Programming Model
IAsyncResult result = Dns.BeginGetHostEntry(
args[0], null, null);
// Poll for completion information.
while (result.IsCompleted != true)
{
…
}
// EndGetHostByName blocks until complete.
IPHostEntry host = Dns.EndGetHostEntry(result);
string[] aliases = host.Aliases;
.NET2.0+
Event-based Asynchronous Pattern
private SoundPlayer player;
private void InitializeSound()
{
// Create an instance of the SoundPlayer class.
player = new SoundPlayer();
// Listen for the LoadCompleted event.
player.LoadCompleted +=
new AsyncCompletedEventHandler(player_LoadCompleted);
player.SoundLocation = filepathTextbox.Text;
player.Play();
}
private void player_LoadCompleted(
object sender, AsyncCompletedEventArgs e) { }
.NET2.0+
Supplanted by the TPL
• Both APM and EAP 
– “This pattern is no longer recommended for
new development”
• TPL  Task Parallel Library
– http://msdn.microsoft.com/en-
us/library/dd460693%28v=vs.110%29.aspx
.NET4.0+
Supplanted by the TPL
.NET4.0+
Supplanted by the TPL
.NET4.0+
Supplanted by the TPL
Parallel.ForEach(sourceCollection, item => Process(item));
Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());
// Create a task and supply a user delegate
Task taskA = new Task( () =>
Console.WriteLine("Hello from taskA."));
// Start the task.
taskA.Start();
// Output a message from the calling thread.
Console.WriteLine("Hello from thread '{0}'.",
Thread.CurrentThread.Name);
taskA.Wait();
.NET4.0+
The New Hotness!
• TAP – Task-based Asynchronous Pattern
• async and await
• So… Why bother?
– Simpler than APM and EAP
– Simpler than raw TPL
Builds on the TPL
.NET4.5
Task-based Asynchronous Pattern
private async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
string urlContents = await client.GetStringAsync(
"http://msdn.microsoft.com");
return urlContents.Length;
}
Agenda
• What is Async?
• Why bother?
• How does this work?
• Gotchas
• Best Practices & More Details
• Next Steps
How does this work?
Task-based Asynchronous Pattern
private async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
string urlContents = await client.GetStringAsync(
"http://msdn.microsoft.com");
return urlContents.Length;
}
1. Before await
2. Await Task
3. Post await
2. “Awaitable”
3. Continuation
0. For compiler
How does this work?
Gimme the Code!
void IAsyncStateMachine.MoveNext()
{
string result = null;
try
{
int num = state;
//if (!Stop)
if (num != -3)
{
TaskAwaiter<string> taskAwaiter;
// Machine starts with num=-1 so we enter
if (num != 0)
{
// First (+ initial) state code, run code before await is invoked
httpClient = new HttpClient();
Debug.WriteLine("before await");
// A task is invoked
taskAwaiter = httpClient.GetStringAsync(url).GetAwaiter();
Gimme the Code!
Whole
Lotta
Code!
How does it work?
• Generates a state machine for every
async call
• SynchronizationContext
• Continuation Tasks
How does it work?
• SynchronizationContext
– Provides a way to queue a unit of work to a
context, not to a specific thread
– Keeps a queue and count of work to do
– Every thread has a current context
– http://msdn.microsoft.com/en-us/magazine/gg598924.aspx
How does it work?
• SynchronizationContext Implementations:
– WindowsFormsSynchronizationContext
– DispatcherSynchronizationContext
• WPF and SilverLight
– WinRTSynchronizationContext
– AspNetSynchronizationContext
• ASP.NET thread pool
– Default SynchronizationContext
• ThreadPool
How does it work?
• Continuation Tasks
– On completion of one task, invoke another
// The antecedent task. Can also be created with Task.Factory.StartNew.
Task<DayOfWeek> taskA = new Task<DayOfWeek>(() => DateTime.Today.DayOfWeek);
// The continuation. Its delegate takes the antecedent task
// as an argument and can return a different type.
Task<string> continuation = taskA.ContinueWith((antecedent) =>
{
return String.Format("Today is {0}.", antecedent.Result);
});
// Start the antecedent.
taskA.Start();
// Use the contuation's result.
Console.WriteLine(continuation.Result);
Task-based Asynchronous Pattern
private async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
string urlContents = await client.GetStringAsync(
"http://msdn.microsoft.com");
return urlContents.Length;
}
1. Before await
2. Await Task
3. Post await
2. “Awaitable”
3. Continuation
0. For compiler
Agenda
• What is Async?
• Why bother?
• How does this work?
• Gotchas
• Best Practices & More Details
• Next Steps
Gotchas…
• Requirements
– You must use the async keyword to await
– void events may need marked with async
public void Blah  public async Task BlahAsync
• Limitations
– You cannot declare ref or out parameters on
an async method
Gotchas…
• When you can’t await async methods
– Inside catch and finally blocks
– Inside properties
– Inside a lock block
– In an unsafe region
– Within most portions of a LINQ query
Gotchas…
• Deadlock and Race conditions, oh my!
var delayTask = DelayAsync();
delayTask.Wait();
Agenda
• What is Async?
• Why bother?
• How does this work?
• Gotchas
• Best Practices & More
Details
• Next Steps
Best Practices & More Details
• Name async methods BlahBlahAsync
• End to end
– Cascading Async
Best Practices & More Details
• Configuring ASP.NET
– Increase App Pool’s queue limit
– AsyncTimeout
• Async in ASP.NET page lifecycle events
%@Page ... Async=“true” %
RegisterAsyncTask(
new PageAsyncTask(GetDataAsync));
http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4
http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45
Best Practices & More Details
• Unit testing
– You can test async methods
[TestMethod]
public async Task GivenBlah…() {
var result = await testClass.DoSomethingAsync();
}
– You can mock async method calls
mockDownloadContent.Setup(x => x.DoSomethingAsync())
.Returns(Task.FromResult<string>(expectedResult));
Best Practices & More Details
• Entity Framework 6
– ApplicationDbContext
await context.Categories.Include(
c => c.Products).LoadAsync();
int savedCount =
await context.SaveChangesAsync();
– QueryableExtensions
var employeeCount = await query.CountAsync();
var firstEmployee = await query.FirstAsync();
https://entityframework.codeplex.com/wikipage?title=Task-based%20Asynchronous%20Pattern%20support%20in%20EF
Best Practices & More Details
• Executing tasks in parallel
await Task1Async();
await Task2Async();
await Task3Async();
await Task.WhenAll(Task1Async(),
Task2Async(),
Task3Async());
Best Practices & More Details
• Death by a thousand cuts
– Batch up async calls
• ConfigureAwait(false)
http://msdn.microsoft.com/en-us/magazine/hh456402.aspx
Best Practices & More Details
• await Task.Yield()
http://msdn.microsoft.com/en-us/library/hh873173%28v=vs.110%29.aspx
• Task cancellation
http://msdn.microsoft.com/en-us/library/jj155759.aspx
• Reporting progress
http://simonsdotnet.wordpress.com/2013/10/11/updating-your-ui-asynchronously-
part-3-reporting-progress/
Agenda
• What is Async?
• Why bother?
• How does this work?
• Gotchas
• Best Practices
• Next Steps
References
• Asynchronous Programming Patterns
– http://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx
• Async and await FAQ
• Steven Cleary’s blog
• Channel 9
• Stephen Toub: The Costs of Async
– http://msdn.microsoft.com/en-us/magazine/hh456402.aspx
Thank You!

Weitere ähnliche Inhalte

Was ist angesagt?

Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Mindfire Solutions
 
Node.js - Advanced Basics
Node.js - Advanced BasicsNode.js - Advanced Basics
Node.js - Advanced BasicsDoug Jones
 
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
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
 
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
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
Asynchronous job queues with python-rq
Asynchronous job queues with python-rqAsynchronous job queues with python-rq
Asynchronous job queues with python-rqAshish Acharya
 
Developer-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneDeveloper-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneSylvain Zimmer
 
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 with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with RxjavaChristophe Marchal
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Particular Software
 
Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013slandelle
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexAkshay Varu
 
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
 

Was ist angesagt? (20)

Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
 
Node.js - Advanced Basics
Node.js - Advanced BasicsNode.js - Advanced Basics
Node.js - Advanced Basics
 
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
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
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...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Asynchronous job queues with python-rq
Asynchronous job queues with python-rqAsynchronous job queues with python-rq
Asynchronous job queues with python-rq
 
Developer-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneDeveloper-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing one
 
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
 
AMC Minor Technical Issues
AMC Minor Technical IssuesAMC Minor Technical Issues
AMC Minor Technical Issues
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps
 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
 
Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
 
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
 

Ähnlich wie End to-end async and await

Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)Panagiotis Kanavos
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web FrameworkDaniel Woods
 
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
 
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...Dan Halperin
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Building Efficient and Reliable Crawler System With Sidekiq Enterprise
Building Efficient and Reliable Crawler System With Sidekiq EnterpriseBuilding Efficient and Reliable Crawler System With Sidekiq Enterprise
Building Efficient and Reliable Crawler System With Sidekiq EnterpriseGary Chu
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Sri Kanth
 
Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...Databricks
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptxssuser35fdf2
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextPrateek Maheshwari
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaYardena Meymann
 
Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019Eliran Eliassy
 

Ähnlich wie End to-end async and await (20)

Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web Framework
 
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
 
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
Introduction to Apache Beam & No Shard Left Behind: APIs for Massive Parallel...
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Building Efficient and Reliable Crawler System With Sidekiq Enterprise
Building Efficient and Reliable Crawler System With Sidekiq EnterpriseBuilding Efficient and Reliable Crawler System With Sidekiq Enterprise
Building Efficient and Reliable Crawler System With Sidekiq Enterprise
 
Intro to CakePHP
Intro to CakePHPIntro to CakePHP
Intro to CakePHP
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012
 
Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptx
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019
 
[Struyf] Automate Your Tasks With Azure Functions
[Struyf] Automate Your Tasks With Azure Functions[Struyf] Automate Your Tasks With Azure Functions
[Struyf] Automate Your Tasks With Azure Functions
 

Kürzlich hochgeladen

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
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
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 

Kürzlich hochgeladen (20)

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
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
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 

End to-end async and await

  • 1. End-to-End Async and Await Vince Fabro Cardinal Solutions Practice Manager, Enterprise App Dev @vfabro
  • 2. Agenda • What is Async? • Why bother? • How does this work? • Gotchas • Best Practices & More Details • Next Steps
  • 3. Agenda • What is Async? • Why bother? • How does this work? • Gotchas • Best Practices & More Details • Next Steps
  • 4. What is Async? • C# 5.0 and .NET 4.5 • async and await keywords • Asynchronous programming for the masses!
  • 5. What is Async? • Asynchronous == Parallel? • Asynchronous == Multithreaded? • Asynchronous == Easy?
  • 6. Agenda • What is Async? • Why bother? • How does this work? • Gotchas • Best Practices & More Details • Next Steps
  • 7. Why bother? • Improve app responsiveness • Simplify asynchronous programming  more approachable Simpler / More approachable than what?
  • 8. Asynchrony the good old way • [… as opposed to the much worse older ways] • APM and EAP • APM – Asynchronous Programming Model – http://msdn.microsoft.com/en-us/library/ms228963%28v=vs.110%29.aspx – http://msdn.microsoft.com/en-us/magazine/cc163467.aspx • EAP – Event-based Asynchronous Pattern – http://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx
  • 9. Asynchronous Programming Model IAsyncResult result = Dns.BeginGetHostEntry( args[0], null, null); // Poll for completion information. while (result.IsCompleted != true) { … } // EndGetHostByName blocks until complete. IPHostEntry host = Dns.EndGetHostEntry(result); string[] aliases = host.Aliases; .NET2.0+
  • 10. Event-based Asynchronous Pattern private SoundPlayer player; private void InitializeSound() { // Create an instance of the SoundPlayer class. player = new SoundPlayer(); // Listen for the LoadCompleted event. player.LoadCompleted += new AsyncCompletedEventHandler(player_LoadCompleted); player.SoundLocation = filepathTextbox.Text; player.Play(); } private void player_LoadCompleted( object sender, AsyncCompletedEventArgs e) { } .NET2.0+
  • 11. Supplanted by the TPL • Both APM and EAP  – “This pattern is no longer recommended for new development” • TPL  Task Parallel Library – http://msdn.microsoft.com/en- us/library/dd460693%28v=vs.110%29.aspx .NET4.0+
  • 12. Supplanted by the TPL .NET4.0+
  • 13. Supplanted by the TPL .NET4.0+
  • 14. Supplanted by the TPL Parallel.ForEach(sourceCollection, item => Process(item)); Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork()); // Create a task and supply a user delegate Task taskA = new Task( () => Console.WriteLine("Hello from taskA.")); // Start the task. taskA.Start(); // Output a message from the calling thread. Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name); taskA.Wait(); .NET4.0+
  • 15. The New Hotness! • TAP – Task-based Asynchronous Pattern • async and await • So… Why bother? – Simpler than APM and EAP – Simpler than raw TPL Builds on the TPL .NET4.5
  • 16. Task-based Asynchronous Pattern private async Task<int> AccessTheWebAsync() { HttpClient client = new HttpClient(); string urlContents = await client.GetStringAsync( "http://msdn.microsoft.com"); return urlContents.Length; }
  • 17. Agenda • What is Async? • Why bother? • How does this work? • Gotchas • Best Practices & More Details • Next Steps
  • 18. How does this work?
  • 19.
  • 20. Task-based Asynchronous Pattern private async Task<int> AccessTheWebAsync() { HttpClient client = new HttpClient(); string urlContents = await client.GetStringAsync( "http://msdn.microsoft.com"); return urlContents.Length; } 1. Before await 2. Await Task 3. Post await 2. “Awaitable” 3. Continuation 0. For compiler
  • 21. How does this work?
  • 22. Gimme the Code! void IAsyncStateMachine.MoveNext() { string result = null; try { int num = state; //if (!Stop) if (num != -3) { TaskAwaiter<string> taskAwaiter; // Machine starts with num=-1 so we enter if (num != 0) { // First (+ initial) state code, run code before await is invoked httpClient = new HttpClient(); Debug.WriteLine("before await"); // A task is invoked taskAwaiter = httpClient.GetStringAsync(url).GetAwaiter();
  • 24. How does it work? • Generates a state machine for every async call • SynchronizationContext • Continuation Tasks
  • 25. How does it work? • SynchronizationContext – Provides a way to queue a unit of work to a context, not to a specific thread – Keeps a queue and count of work to do – Every thread has a current context – http://msdn.microsoft.com/en-us/magazine/gg598924.aspx
  • 26. How does it work? • SynchronizationContext Implementations: – WindowsFormsSynchronizationContext – DispatcherSynchronizationContext • WPF and SilverLight – WinRTSynchronizationContext – AspNetSynchronizationContext • ASP.NET thread pool – Default SynchronizationContext • ThreadPool
  • 27. How does it work? • Continuation Tasks – On completion of one task, invoke another // The antecedent task. Can also be created with Task.Factory.StartNew. Task<DayOfWeek> taskA = new Task<DayOfWeek>(() => DateTime.Today.DayOfWeek); // The continuation. Its delegate takes the antecedent task // as an argument and can return a different type. Task<string> continuation = taskA.ContinueWith((antecedent) => { return String.Format("Today is {0}.", antecedent.Result); }); // Start the antecedent. taskA.Start(); // Use the contuation's result. Console.WriteLine(continuation.Result);
  • 28. Task-based Asynchronous Pattern private async Task<int> AccessTheWebAsync() { HttpClient client = new HttpClient(); string urlContents = await client.GetStringAsync( "http://msdn.microsoft.com"); return urlContents.Length; } 1. Before await 2. Await Task 3. Post await 2. “Awaitable” 3. Continuation 0. For compiler
  • 29. Agenda • What is Async? • Why bother? • How does this work? • Gotchas • Best Practices & More Details • Next Steps
  • 30. Gotchas… • Requirements – You must use the async keyword to await – void events may need marked with async public void Blah  public async Task BlahAsync • Limitations – You cannot declare ref or out parameters on an async method
  • 31. Gotchas… • When you can’t await async methods – Inside catch and finally blocks – Inside properties – Inside a lock block – In an unsafe region – Within most portions of a LINQ query
  • 32. Gotchas… • Deadlock and Race conditions, oh my! var delayTask = DelayAsync(); delayTask.Wait();
  • 33. Agenda • What is Async? • Why bother? • How does this work? • Gotchas • Best Practices & More Details • Next Steps
  • 34. Best Practices & More Details • Name async methods BlahBlahAsync • End to end – Cascading Async
  • 35. Best Practices & More Details • Configuring ASP.NET – Increase App Pool’s queue limit – AsyncTimeout • Async in ASP.NET page lifecycle events %@Page ... Async=“true” % RegisterAsyncTask( new PageAsyncTask(GetDataAsync)); http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4 http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45
  • 36. Best Practices & More Details • Unit testing – You can test async methods [TestMethod] public async Task GivenBlah…() { var result = await testClass.DoSomethingAsync(); } – You can mock async method calls mockDownloadContent.Setup(x => x.DoSomethingAsync()) .Returns(Task.FromResult<string>(expectedResult));
  • 37. Best Practices & More Details • Entity Framework 6 – ApplicationDbContext await context.Categories.Include( c => c.Products).LoadAsync(); int savedCount = await context.SaveChangesAsync(); – QueryableExtensions var employeeCount = await query.CountAsync(); var firstEmployee = await query.FirstAsync(); https://entityframework.codeplex.com/wikipage?title=Task-based%20Asynchronous%20Pattern%20support%20in%20EF
  • 38. Best Practices & More Details • Executing tasks in parallel await Task1Async(); await Task2Async(); await Task3Async(); await Task.WhenAll(Task1Async(), Task2Async(), Task3Async());
  • 39. Best Practices & More Details • Death by a thousand cuts – Batch up async calls • ConfigureAwait(false) http://msdn.microsoft.com/en-us/magazine/hh456402.aspx
  • 40. Best Practices & More Details • await Task.Yield() http://msdn.microsoft.com/en-us/library/hh873173%28v=vs.110%29.aspx • Task cancellation http://msdn.microsoft.com/en-us/library/jj155759.aspx • Reporting progress http://simonsdotnet.wordpress.com/2013/10/11/updating-your-ui-asynchronously- part-3-reporting-progress/
  • 41. Agenda • What is Async? • Why bother? • How does this work? • Gotchas • Best Practices • Next Steps
  • 42. References • Asynchronous Programming Patterns – http://msdn.microsoft.com/en-us/library/wewwczdw%28v=vs.110%29.aspx • Async and await FAQ • Steven Cleary’s blog • Channel 9 • Stephen Toub: The Costs of Async – http://msdn.microsoft.com/en-us/magazine/hh456402.aspx

Hinweis der Redaktion

  1. Have been in Tampa for almost 2 months. Excited to be here and looking forward to engaging with the community. We have built very strong successful relationships with many Fortune 1000/500/1 clients in our other cities.
  2. Here is a quick snapshot of some of those companies. The majority, if not all of these clients are ongoing/established relationships…not a one and done.
  3. Involving our UX team in our technology discussions is crucial. Building an application with the user in mind is important but so is designing for the technology. Our UX team understands the technology, whether it be mobile, web dev, SharePoint, etc. which has allowed us to become a go-to UX shop for many of the clients I mentioned. More recently our UX is engaging on most of our BI projects as self-service becomes important, users need to be able to find and manipulate their data quickly and easily.
  4. My intention is an end-to-end, breadth first approach, although perhaps not very deep in some areas
  5. Need a dashboard for customer account viewBuild presentations for customers for design and cost analysisProcessDeliverables
  6. Need a dashboard for customer account viewBuild presentations for customers for design and cost analysisProcessDeliverables