SlideShare una empresa de Scribd logo
1 de 25
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/

Más contenido relacionado

La actualidad más candente

MPI-3 Timer requests proposal
MPI-3 Timer requests proposalMPI-3 Timer requests proposal
MPI-3 Timer requests proposalJeff Squyres
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascriptEman 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 ProgrammingOlivier NAVARRE
 
Dangers of parallel streams
Dangers of parallel streamsDangers of parallel streams
Dangers of parallel streamsLukáš 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ónGlobant
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett 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 FiberReact 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
 

La actualidad más candente (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 a Introducing C# Async CTP

Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
 
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 TaskKouji Matsui
 
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 FlinkAljoscha Krettek
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin 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.pdfEngmohammedAlzared
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Pythongturnquist
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NETPierre-Luc Maheu
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Ordina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina 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
 
Workflow Management with Espresso Workflow
Workflow Management with Espresso WorkflowWorkflow Management with Espresso Workflow
Workflow Management with Espresso WorkflowRolf Kremer
 

Similar a Introducing 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
 
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#)
 
Workflow Management with Espresso Workflow
Workflow Management with Espresso WorkflowWorkflow Management with Espresso Workflow
Workflow Management with Espresso Workflow
 

Más de 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 2020Pratik Khasnabis
 
Microsoft Azure fundamentals for AWS practitioners
Microsoft Azure fundamentals for AWS practitionersMicrosoft Azure fundamentals for AWS practitioners
Microsoft Azure fundamentals for AWS practitionersPratik 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 templatesPratik 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.0Pratik 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 TemplatesPratik 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 2Pratik Khasnabis
 

Más de 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
 

Último

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Último (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Introducing 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/