SlideShare a Scribd company logo
Introducing C# Async CTP Pratik Khasnabis DDD Melbourne 2011
About Me Lead .Net Developer BUPA Australia Pratik Khasnabis Work For Tweet as C# Disclaimer: The opinions and viewpoints expressed in this presentation are my own and are not necessarily those of my employer, BUPA Australia.  Solution Design @softveda WCF & SOA
What you will learn today ? Why is asynchronous programming important The Task-Based Asynchronous Pattern (TAP) Convert synchronous version of a code to asynchronous Using current pattern Using the new pattern Add Cancellation and Error Handling Add Progress Reporting
What you will NOT learn today ? The implementation details on how the pattern works Other features introduced in the CTP Concurrent programming using the TPL TPL Dataflow
Why Async ?
Why Asynchronous ? Responsive UI Waiting on I/O or long computation will stop message processing and hang the app Becoming ubiquitous. JavaScript and Silverlight Responsive services Execute multiple operations simultaneously, receiving notifications when each completes Scalable. Serve many requests on a small pool of threads Do NOT block threads.
Threads are not the answer Thread creation is expensive Each managed thread takes 1MB of stack space Context switching is expensive Writing asynchronous methods is difficult Using callbacks for continuations Error handling, Cancellation, Progress Reporting is complicated Doesn’t feel natural How to be Asynchronous ?
Asynchronous Programming Model public class Stream { public intRead(byte[] buffer, intoffset, intcount); public IAsyncResultBeginRead(byte[] buffer, intoffset, intcount, AsyncCallbackcallback, object state); public intEndRead(IAsyncResultasyncResult); }
Event-Based Asynchronous Pattern public class Stream { public void ReadAsync(byte[] buffer, intoffset, intcount);   public event ReadCompletedEventHandlerReadCompleted; } public delegate void ReadCompletedEventHandler(object sender, ReadCompletedEventArgseventArgs); public class ReadCompletedEventArgs: AsyncCompletedEventArgs { public intResult { get; } }
Demo
C# and VB.NetAsync CTP First introduced in PDC 2010 and the refresh in MIX 2011 (VS 2010 SP1) Introduces async and await contextual keywords in C# Available for Silverlight and Windows Phone 7 development as well Goal – Asynchronous programming should work as simply and intuitively as the synchronous version
Demo
Sync => Async Add reference to the Async CTP Library
Sync => Async Add asyncmodifier to the return types Change return type to Task<TResult> Add Async suffix to the method name Change to DownloadStringTaskAsync Add await keyword before the call of the Async method Keep doing this until we reach a void returning method up in the call hierarchy. Add asyncmodifier before the void
C# Async Features Asynchronous methods (and lambdas, and anonymous delegates) are a new feature in C# Asynchronous methods have an async modifier Asynchronous methods must return void, Task or Task<TResult> Asynchronous method names ends with an “Async” suffix by convention
C# AsyncFeatures, contd. Asynchronous methods can have small synchronous statements Asynchronous methods should have one or more await expressions inside it C# compiler does two things for an await expression 1. Creates a continuation for the rest of the method and assigns it to the Awaiter 2. Returns from the async method immediately after awaiting
C# Async Features, end. Asynchronous methods with void return type are fire-and-forget Cannot be awaited on Top level methods or event handlers Asynchronous methods with Task or Task<T> return type can be awaited They resume execution once the awaited task completes In between no thread is occupied Execution continues
Task-Based Async Pattern public class Stream { public Task<int> ReadAsync(byte[] buffer, intoffset, intcount);   public Task<int>ReadAsync(byte[] buffer, intoffset, intcount, CancellationTokencancellationToken, IProgress<T>progress);   }
Tracing the control flow Caller Void Async Method Task AsyncMethod Awaitable UI thread IOCP thread async void LoadPhotosAsync(string tag) {  … var photosTask =  GetPhotosAsync(tag, page);  var photos = awaitphotosTask; DisplayPhotos(photos);  } async Task<FlickrPhoto[]>  GetPhotosAsync(string tag, int page)  { WebClient client = new WebClient();  var IOTask = client.DownloadStringTaskAsync(…);  var apiResponse = await IOTask; var photos = ParseResponse(apiResponse); return photos; } Button Click I/O Task 2 2 1 UI Task C1 Download Done C1 1 C1 C2 C2
Asynchronous ≠ Concurrent Hang UI Thread UI Messages DisplayPhotos Just One Thread !! DownloadDataAsync ParseResponse
Asynchronous ≠ Concurrent  Asynchronous operations can share a single thread for multiple control flows The UI and IOCP threads are provided by the CLR or OS for free. Use them. Co-Operative multitasking. Wait for tasks to finish and yield control flow while awaiting. Task and Task<T> represents an operation that will return a result in “future”. Not tied to a thread.
Implementation The type of the expression awaited is based on a pattern satisfied by Task and Task<T> GetAwaiter/IsCompleted/OnCompleted/GetResult. C# compiler generates a state machine
Task-Based Async Pattern TAP methods return Task or Task<TResult> TAP methods ends with an “Async” suffix by convention TAP methods should have the same parameters as the synchronous one in the same order Avoid out and ref parameters Can have CancellationToken parameter Can have IProgress<T> parameter
TaskEx TaskEx.Delay() TaskEx.Run() TaskEx.WhenAll() TaskEx.WhenAny() TaskEx.Yield()
Resources CTP - http://msdn.microsoft.com/en-us/vstudio/gg316360 C# - http://blogs.msdn.com/b/ericlippert/ Jon Skeet (implementation details) https://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx VB.Net - http://blogs.msdn.com/b/lucian/

More Related Content

What's hot

Async/Await
Async/AwaitAsync/Await
Async/Await
Jeff Hart
 
MPI-3 Timer requests proposal
MPI-3 Timer requests proposalMPI-3 Timer requests proposal
MPI-3 Timer requests proposal
Jeff Squyres
 
Hidden Dragons of CGO
Hidden Dragons of CGOHidden Dragons of CGO
Hidden Dragons of CGO
All Things Open
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
Eman Mohamed
 
MERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingMERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel Programming
Olivier NAVARRE
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
shuklagirish
 
Dangers of parallel streams
Dangers of parallel streamsDangers of parallel streams
Dangers of parallel streams
Lukáš Křečan
 
Apache Beam: Lote portátil y procesamiento de transmisión
Apache Beam: Lote portátil y procesamiento de transmisiónApache Beam: Lote portátil y procesamiento de transmisión
Apache Beam: Lote portátil y procesamiento de transmisión
Globant
 
The future of templating and frameworks
The future of templating and frameworksThe future of templating and frameworks
The future of templating and frameworks
Filip Bruun Bech-Larsen
 
Async await
Async awaitAsync await
Async await
Jeff Hart
 
Revealing C# 5
Revealing C# 5Revealing C# 5
Revealing C# 5
Praveen Prajapati
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Igalia
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
Bohdan Pashkovskyi
 
Raphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React FiberRaphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React Fiber
React Conf Brasil
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
Calvin Cheng
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 

What's hot (18)

Async/Await
Async/AwaitAsync/Await
Async/Await
 
MPI-3 Timer requests proposal
MPI-3 Timer requests proposalMPI-3 Timer requests proposal
MPI-3 Timer requests proposal
 
Hidden Dragons of CGO
Hidden Dragons of CGOHidden Dragons of CGO
Hidden Dragons of CGO
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
MERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingMERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel Programming
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
CSharp 5 Async
CSharp 5 AsyncCSharp 5 Async
CSharp 5 Async
 
Dangers of parallel streams
Dangers of parallel streamsDangers of parallel streams
Dangers of parallel streams
 
Apache Beam: Lote portátil y procesamiento de transmisión
Apache Beam: Lote portátil y procesamiento de transmisiónApache Beam: Lote portátil y procesamiento de transmisión
Apache Beam: Lote portátil y procesamiento de transmisión
 
The future of templating and frameworks
The future of templating and frameworksThe future of templating and frameworks
The future of templating and frameworks
 
Async await
Async awaitAsync await
Async await
 
Revealing C# 5
Revealing C# 5Revealing C# 5
Revealing C# 5
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
 
Raphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React FiberRaphael Amorim - Scrating React Fiber
Raphael Amorim - Scrating React Fiber
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 

Similar to Ddd melbourne 2011 C# async ctp

Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
Craig Dunn
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
Pratik Khasnabis
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
Betclic Everest Group Tech Team
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
How to meets Async and Task
How to meets Async and TaskHow to meets Async and Task
How to meets Async and Task
Kouji Matsui
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
Soacat Blogspot
 
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Flink Forward
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4Wei Sun
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingOliver Scheer
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on Flink
Aljoscha Krettek
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
Marcin Tyborowski
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
EngmohammedAlzared
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
Riccardo Terrell
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
gturnquist
 
AsynchronousProgrammingDesignPatterns.pptx
AsynchronousProgrammingDesignPatterns.pptxAsynchronousProgrammingDesignPatterns.pptx
AsynchronousProgrammingDesignPatterns.pptx
Abhishek Sagar
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
Pierre-Luc Maheu
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
Rob Tweed
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Ordina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTP
Ordina Belgium
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 

Similar to Ddd melbourne 2011 C# async ctp (20)

Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
How to meets Async and Task
How to meets Async and TaskHow to meets Async and Task
How to meets Async and Task
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
Flink Forward Berlin 2018: Thomas Weise & Aljoscha Krettek - "Python Streamin...
 
Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on Flink
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
AsynchronousProgrammingDesignPatterns.pptx
AsynchronousProgrammingDesignPatterns.pptxAsynchronousProgrammingDesignPatterns.pptx
AsynchronousProgrammingDesignPatterns.pptx
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Ordina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTP
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 

More from Pratik Khasnabis

Open API (aka Swagger) - DDD by Night May 2020
Open API (aka Swagger) - DDD by Night May 2020Open API (aka Swagger) - DDD by Night May 2020
Open API (aka Swagger) - DDD by Night May 2020
Pratik Khasnabis
 
Whats new in .net core 3
Whats new in .net core 3Whats new in .net core 3
Whats new in .net core 3
Pratik Khasnabis
 
Containers on Windows
Containers on WindowsContainers on Windows
Containers on Windows
Pratik Khasnabis
 
Microsoft Azure fundamentals for AWS practitioners
Microsoft Azure fundamentals for AWS practitionersMicrosoft Azure fundamentals for AWS practitioners
Microsoft Azure fundamentals for AWS practitioners
Pratik Khasnabis
 
Deploying a website in Azure using ARM templates
Deploying a website in Azure using ARM templatesDeploying a website in Azure using ARM templates
Deploying a website in Azure using ARM templates
Pratik Khasnabis
 
What is .Net Standard
What is .Net StandardWhat is .Net Standard
What is .Net Standard
Pratik Khasnabis
 
Recapping C# 6.0 and A First Look Into C# 7.0
Recapping C# 6.0 and A First Look Into C# 7.0Recapping C# 6.0 and A First Look Into C# 7.0
Recapping C# 6.0 and A First Look Into C# 7.0
Pratik Khasnabis
 
Deploy a Website in Azure using ARM Templates
Deploy a Website in Azure using ARM TemplatesDeploy a Website in Azure using ARM Templates
Deploy a Website in Azure using ARM Templates
Pratik Khasnabis
 
DDD Melbourne 2014 security in ASP.Net Web API 2
DDD Melbourne 2014 security in ASP.Net Web API 2DDD Melbourne 2014 security in ASP.Net Web API 2
DDD Melbourne 2014 security in ASP.Net Web API 2
Pratik Khasnabis
 

More from Pratik Khasnabis (9)

Open API (aka Swagger) - DDD by Night May 2020
Open API (aka Swagger) - DDD by Night May 2020Open API (aka Swagger) - DDD by Night May 2020
Open API (aka Swagger) - DDD by Night May 2020
 
Whats new in .net core 3
Whats new in .net core 3Whats new in .net core 3
Whats new in .net core 3
 
Containers on Windows
Containers on WindowsContainers on Windows
Containers on Windows
 
Microsoft Azure fundamentals for AWS practitioners
Microsoft Azure fundamentals for AWS practitionersMicrosoft Azure fundamentals for AWS practitioners
Microsoft Azure fundamentals for AWS practitioners
 
Deploying a website in Azure using ARM templates
Deploying a website in Azure using ARM templatesDeploying a website in Azure using ARM templates
Deploying a website in Azure using ARM templates
 
What is .Net Standard
What is .Net StandardWhat is .Net Standard
What is .Net Standard
 
Recapping C# 6.0 and A First Look Into C# 7.0
Recapping C# 6.0 and A First Look Into C# 7.0Recapping C# 6.0 and A First Look Into C# 7.0
Recapping C# 6.0 and A First Look Into C# 7.0
 
Deploy a Website in Azure using ARM Templates
Deploy a Website in Azure using ARM TemplatesDeploy a Website in Azure using ARM Templates
Deploy a Website in Azure using ARM Templates
 
DDD Melbourne 2014 security in ASP.Net Web API 2
DDD Melbourne 2014 security in ASP.Net Web API 2DDD Melbourne 2014 security in ASP.Net Web API 2
DDD Melbourne 2014 security in ASP.Net Web API 2
 

Recently uploaded

Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

Ddd melbourne 2011 C# async ctp

  • 1. Introducing C# Async CTP Pratik Khasnabis DDD Melbourne 2011
  • 2. About Me Lead .Net Developer BUPA Australia Pratik Khasnabis Work For Tweet as C# Disclaimer: The opinions and viewpoints expressed in this presentation are my own and are not necessarily those of my employer, BUPA Australia. Solution Design @softveda WCF & SOA
  • 3. What you will learn today ? Why is asynchronous programming important The Task-Based Asynchronous Pattern (TAP) Convert synchronous version of a code to asynchronous Using current pattern Using the new pattern Add Cancellation and Error Handling Add Progress Reporting
  • 4. What you will NOT learn today ? The implementation details on how the pattern works Other features introduced in the CTP Concurrent programming using the TPL TPL Dataflow
  • 6. Why Asynchronous ? Responsive UI Waiting on I/O or long computation will stop message processing and hang the app Becoming ubiquitous. JavaScript and Silverlight Responsive services Execute multiple operations simultaneously, receiving notifications when each completes Scalable. Serve many requests on a small pool of threads Do NOT block threads.
  • 7. Threads are not the answer Thread creation is expensive Each managed thread takes 1MB of stack space Context switching is expensive Writing asynchronous methods is difficult Using callbacks for continuations Error handling, Cancellation, Progress Reporting is complicated Doesn’t feel natural How to be Asynchronous ?
  • 8. Asynchronous Programming Model public class Stream { public intRead(byte[] buffer, intoffset, intcount); public IAsyncResultBeginRead(byte[] buffer, intoffset, intcount, AsyncCallbackcallback, object state); public intEndRead(IAsyncResultasyncResult); }
  • 9. Event-Based Asynchronous Pattern public class Stream { public void ReadAsync(byte[] buffer, intoffset, intcount); public event ReadCompletedEventHandlerReadCompleted; } public delegate void ReadCompletedEventHandler(object sender, ReadCompletedEventArgseventArgs); public class ReadCompletedEventArgs: AsyncCompletedEventArgs { public intResult { get; } }
  • 10. Demo
  • 11. C# and VB.NetAsync CTP First introduced in PDC 2010 and the refresh in MIX 2011 (VS 2010 SP1) Introduces async and await contextual keywords in C# Available for Silverlight and Windows Phone 7 development as well Goal – Asynchronous programming should work as simply and intuitively as the synchronous version
  • 12. Demo
  • 13. Sync => Async Add reference to the Async CTP Library
  • 14. Sync => Async Add asyncmodifier to the return types Change return type to Task<TResult> Add Async suffix to the method name Change to DownloadStringTaskAsync Add await keyword before the call of the Async method Keep doing this until we reach a void returning method up in the call hierarchy. Add asyncmodifier before the void
  • 15. C# Async Features Asynchronous methods (and lambdas, and anonymous delegates) are a new feature in C# Asynchronous methods have an async modifier Asynchronous methods must return void, Task or Task<TResult> Asynchronous method names ends with an “Async” suffix by convention
  • 16. C# AsyncFeatures, contd. Asynchronous methods can have small synchronous statements Asynchronous methods should have one or more await expressions inside it C# compiler does two things for an await expression 1. Creates a continuation for the rest of the method and assigns it to the Awaiter 2. Returns from the async method immediately after awaiting
  • 17. C# Async Features, end. Asynchronous methods with void return type are fire-and-forget Cannot be awaited on Top level methods or event handlers Asynchronous methods with Task or Task<T> return type can be awaited They resume execution once the awaited task completes In between no thread is occupied Execution continues
  • 18. Task-Based Async Pattern public class Stream { public Task<int> ReadAsync(byte[] buffer, intoffset, intcount); public Task<int>ReadAsync(byte[] buffer, intoffset, intcount, CancellationTokencancellationToken, IProgress<T>progress); }
  • 19. Tracing the control flow Caller Void Async Method Task AsyncMethod Awaitable UI thread IOCP thread async void LoadPhotosAsync(string tag) { … var photosTask =  GetPhotosAsync(tag, page); var photos = awaitphotosTask; DisplayPhotos(photos); } async Task<FlickrPhoto[]>  GetPhotosAsync(string tag, int page) { WebClient client = new WebClient(); var IOTask = client.DownloadStringTaskAsync(…); var apiResponse = await IOTask; var photos = ParseResponse(apiResponse); return photos; } Button Click I/O Task 2 2 1 UI Task C1 Download Done C1 1 C1 C2 C2
  • 20. Asynchronous ≠ Concurrent Hang UI Thread UI Messages DisplayPhotos Just One Thread !! DownloadDataAsync ParseResponse
  • 21. Asynchronous ≠ Concurrent Asynchronous operations can share a single thread for multiple control flows The UI and IOCP threads are provided by the CLR or OS for free. Use them. Co-Operative multitasking. Wait for tasks to finish and yield control flow while awaiting. Task and Task<T> represents an operation that will return a result in “future”. Not tied to a thread.
  • 22. Implementation The type of the expression awaited is based on a pattern satisfied by Task and Task<T> GetAwaiter/IsCompleted/OnCompleted/GetResult. C# compiler generates a state machine
  • 23. Task-Based Async Pattern TAP methods return Task or Task<TResult> TAP methods ends with an “Async” suffix by convention TAP methods should have the same parameters as the synchronous one in the same order Avoid out and ref parameters Can have CancellationToken parameter Can have IProgress<T> parameter
  • 24. TaskEx TaskEx.Delay() TaskEx.Run() TaskEx.WhenAll() TaskEx.WhenAny() TaskEx.Yield()
  • 25. Resources CTP - http://msdn.microsoft.com/en-us/vstudio/gg316360 C# - http://blogs.msdn.com/b/ericlippert/ Jon Skeet (implementation details) https://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx VB.Net - http://blogs.msdn.com/b/lucian/