C# 5.0 Async Pratik KhasnabisDDD Melbourne 2012
About MeQuick backgroundLead Developer at Bupa AustraliaDeveloper for 15 yearsC# & .Net 8 yearsC++ before thatDisclaimerTh...
The need for AsyncResponsive UIUI thread is running as a message pump in a   Touch ready Metro Appsloop                   ...
Async in .Net 4.5First introduced in PDC                                   Two new keywords2010 and the refresh in        ...
.NET 4 and Silverlight 5Async Targeting PackDownload using NuGetMicrosoft.CompilerServices.AsyncTargetingPackDifferences i...
TaskTask                                AwaitersA Task is promise of a              Tasks are the backingresult that will ...
Async and AwaitKeyword: async                           Keyword: awaitOnly methods or lamdbas with async       Makes the r...
Task-Based Async PatternTAP methods has an async modifier ,                                      TAP methods should return...
Async in .Net 4.5 BCLSystem.Xml.XmlReader                                       System.Net.Mailpublic virtual Task<bool>  ...
Async in WPF/WinForms apps Caller         Void Async Method                           Task Async Method                   ...
Concurrency without threads             UI ThreadDownload                         Process                Message Pump  Dat...
Async in Server Apps                                Thread Pool Exhaustion                                                ...
ASP.Net Core ServicesAsynchronous HTTP modules                                 Asynchronous HTTP handlerspublic class MyHt...
ASP.Net MVC 4                                  TimeoutController                        [AsyncTimeout(2000)]Derive from As...
ASP.Net WebForms        Page Markup        <%@ Page Language="C#"        Async="true" AsyncTimeOut="2"        CodeBehind="...
WCFService: Async operations                            Client: Async proxies[ServiceContract]                            ...
VS 2012 Unit TestsAsync Test Methods – return Task     Test Frameworks[TestMethod]                         MS Test – Suppo...
Metro and WinRThttp://blogs.msdn.com/b/windowsappdev/archive/2012/06/14/exposing-net-tasks-as-winrt-asynchronous-operation...
Choosing Sync vs Async            SynchronousOperations are simple or short-running        CPU bound operations    Simplic...
ADO.Net                                     Tabular Data Stream ProtocolWorkerThread                                      ...
ADO.Net                               RecommendationsUse                                        UseCommandBehavior.Sequent...
Resources• http://msdn.microsoft.com/en-US/async• VB.Net - http://blogs.msdn.com/b/lucian/• C# (implementation details) - ...
Upcoming SlideShare
Loading in …5
×

Async Programming in C# 5

4,168 views

Published on

This is a presentation on new Async Programming features in C# 5 at DDD Melbourne 2012 by Pratik Khasnabis

0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,168
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
83
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide
  • http://blogs.msdn.com/b/somasegar/archive/2010/10/28/making-asynchronous-programming-easy.aspxWith Async, our goal now is to make asynchronous programming far more approachable so asynchronous code is as easy to write and maintain as synchronous code. Making your code asynchronous should require only simple changes and should be possible to implement in a non-disruptive manner in your code. At the same time, it should be evident when code is “going async” so that the inherently-concurrent nature of the method can be understood at a glance.
  • http://en.wikipedia.org/wiki/Hollywood_principleThreads are too low levelThreads are not the answerThread creation is expensiveEach managed thread takes 1MB of stack spaceContext switching is expensiveWriting asynchronous methods is difficultUsing callbacks for continuationsError handling, Cancellation, Progress Reporting is complicatedDoesn’t feel natural
  • Asynchronous operations can share a single thread for multiple control flowsThe UI and IOCP threads are provided by the CLR or OS – reuseCo-Operative multitasking. Wait for tasks to finish and yield control flow while awaiting.
  • http://msdn.microsoft.com/en-us/library/ee728598.aspxOn the Web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request. If all available threads might be blocked. This condition is known as thread starvation. When this condition is reached, the Web server queues requests. If the request queue becomes full, the Web server rejects requests with an HTTP 503 status (Server Too Busy). However, during an asynchronous call, the server is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing when there are many requests that invoke long-running operations.When an asynchronous action is invoked, the following steps occur:1. The Web server gets a thread from the thread pool (the worker thread) and schedules it to handle an incoming request. This worker thread initiates an asynchronous operation.2. The worker thread is returned to the thread pool to service another Web request.3. When the asynchronous operation is complete, it notifies ASP.NET.4. The Web server gets a worker thread from the thread pool (which might be a different thread from the thread that started the asynchronous operation) to process the remainder of the request, including rendering the response.http://blogs.msdn.com/b/tmarq/archive/2007/07/21/asp-net-thread-usage-on-iis-7-0-and-6-0.aspx in IIS 7.5 and 7.0 integrated mode, ASP.NET restricts the number of concurrently executing requests. Obviously if the reqeusts are synchronous, then the number of concurrently executing requests is the same as the number of threads concurrently executing requests, but if the requests are asynchronous then these two numbers can be quite different as you could have far more requests than threads.
  • http://www.asp.net/vnext/overview/whitepapers/whats-new
  • http://msdn.microsoft.com/en-us/library/hh420390(v=vs.110).aspx
  • http://msdn.microsoft.com/en-us/library/gg416514(v=vs.108).aspxhttp://blogs.msdn.com/b/nicd/archive/2007/04/16/dissection-of-an-asp-net-2-0-request-processing-flow.aspx
  • http://blogs.msdn.com/b/adonet/archive/2012/04/20/using-sqldatareader-s-new-async-methods-in-net-4-5-beta.aspxhttp://blogs.msdn.com/b/adonet/archive/2012/07/15/using-sqldatareader-s-new-async-methods-in-net-4-5-beta-part-2-examples.aspx
  • In roadmap for Entity Framework 6http://msdn.microsoft.com/en-us/library/hh556234(v=vs.110).aspx
  • Async Programming in C# 5

    1. 1. C# 5.0 Async Pratik KhasnabisDDD Melbourne 2012
    2. 2. About MeQuick backgroundLead Developer at Bupa AustraliaDeveloper for 15 yearsC# & .Net 8 yearsC++ before thatDisclaimerThis presentation is my own and I do notrepresent my company.
    3. 3. The need for AsyncResponsive UIUI thread is running as a message pump in a Touch ready Metro Appsloop In WinRT if an API is likely to takeWaiting on IO or long computation will stop more than 50ms to run the API ismessage processing => Frozen UI asynchronousScalable Server ApplicationsA CLR thread is used to service requestsA blocked thread => less scalableService thousands of IO bound requests on asmall pool of threads
    4. 4. Async in .Net 4.5First introduced in PDC Two new keywords2010 and the refresh in async and awaitMIX 2011 (VS 2010 SP1)An unsupported out-of- Built to take advantage ofband release. Updated C# Task and Task<T>and VB compilers. Introduced in .Net 4.0AsyncCtpLibrary.dll Async methodsintroduced async Pervasive in .Net 4.5extension methods forcommon classes.
    5. 5. .NET 4 and Silverlight 5Async Targeting PackDownload using NuGetMicrosoft.CompilerServices.AsyncTargetingPackDifferences in BehaviourRead the release notesStatic helper methods are in TaskExclass instead of Taske.g. Task.Run(…) vs TaskEx.Run(…) Windows Phone and Azure No support yet
    6. 6. TaskTask AwaitersA Task is promise of a Tasks are the backingresult that will delivered types for async methodsat some time in future in .Net 4.5Compositional Two typesTasks can be composed Taskusing continuations Task<T> AwaitersCancellable Tasks are the backingTasks can be designed to types for async methodsbe cancelled easily in .Net 4.5
    7. 7. Async and AwaitKeyword: async Keyword: awaitOnly methods or lamdbas with async Makes the rest of method amodifier can use the await keyword. continuationReturn type must be void, Task or When the method completesTask<T> execution resumes where it left off onThe method actually returns void or T, the right synchronisation contextthe compile creates the Task object Compiler generates a state machineDoesn’t make the methodasynchronous var awaiter = expression.GetAwaiter(); if (awaiter.IsCompleted) Console.WriteLine (awaiter.GetResult()); elsevar result = await expression; awaiter.OnCompleted (() =><code block> { var result = awaiter.GetResult(); <code block> );
    8. 8. Task-Based Async PatternTAP methods has an async modifier , TAP methods should return quickly toreturns a running Task or caller with a small synchronousTask<TResult> and ends with an phase.“Async” suffix by convention TAP methods should have the same parameters as the synchronous one Avoids out and ref parameters in the same orderCan have CancellationToken Can have IProgress<T> parameterparameter
    9. 9. Async in .Net 4.5 BCLSystem.Xml.XmlReader System.Net.Mailpublic virtual Task<bool> public Task SendMailAsync(ReadAsync() MailMessage message ) System.Net.Http.HttpClientSystem.IO.Stream public Task<string>public Task CopyToAsync( GetStringAsync( stringStream destination ) requestUri ) System.Net.WebSockets public abstractSystem.IO.TextReader Task<WebSocketReceiveResult>public virtual Task<int> ReceiveAsync( ArraySegment<byte>ReadAsync( char[] buffer, buffer, CancellationTokenint index, int count ) cancellationToken )
    10. 10. Async in WPF/WinForms apps Caller Void Async Method Task Async Method AwaitableUI IOCPthread thread async void LoadPhotosAsync(string tag) { async Task<FlickrPhoto[]> … GetPhotosAsync(string tag, int page) var photosTask = GetPhotosAsync(tag, pa { ge); WebClient client = new WebClient(); var webTask = client.DownloadStringTaskAsyn webTask c(…); var apiResponse = await webTask; var photos = await photosTask; var photos = ParseResponse(apiResponse); return photos; DisplayPhotos(photos); } }
    11. 11. Concurrency without threads UI ThreadDownload Process Message Pump Data Data Process UI Events
    12. 12. Async in Server Apps Thread Pool Exhaustion DB ASP.Net IIS IIS I/O Thread Worker Process WS MaxConcurrentRequestsPerCPU Worker Threads File Waiting for I/O ops HTTP.SYS Kernel To complete QueueHTTPRequests
    13. 13. ASP.Net Core ServicesAsynchronous HTTP modules Asynchronous HTTP handlerspublic class MyHttpModule : IHttpModule{ public class MyAsyncHandler :private async TaskScrapeHtmlPage(object caller, EventArgs e) HttpTaskAsyncHandler{ { await ...} public override async Task public void Init(HttpApplication ProcessRequestAsync(HttpContextcontext) { context) EventHandlerTaskAsyncHelper helper = { new EventHandlerTaskAsyncHelper(ScrapeHtmlPage); context.AddOnPostAuthorizeRequestAsync( await … helper.BeginEventHandler, helper.EndEventHandler); } }} }
    14. 14. ASP.Net MVC 4 TimeoutController [AsyncTimeout(2000)]Derive from AsyncController ?? [HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]Actionsasync methods returning Task orTask<ActionResult>
    15. 15. ASP.Net WebForms Page Markup <%@ Page Language="C#" Async="true" AsyncTimeOut="2" CodeBehind="AsyncPage.aspx.cs" %> Page_Load method Register the async method The async mehtod will be asynchronoiusly executed after PreRender stage in page lifecycle
    16. 16. WCFService: Async operations Client: Async proxies[ServiceContract] Use svcutil or Add Service Referencepublic interface IDemoService{ [OperationContract] var proxy = new Task<string> GetStockQuoteAsync(string ticker); StockQuoteService.StockQuoteSoapClie} nt();public class DemoService : IDemoService var quote = await{ proxy.GetQuoteAsync("MSFT"); public async Task<string> GetStockQuoteAsync(string ticker) { await ... }}
    17. 17. VS 2012 Unit TestsAsync Test Methods – return Task Test Frameworks[TestMethod] MS Test – Supports async, Built in testpublic async Task UnitTestMethod() provider{ xUnit – Supports async in v1.9, await Task.Delay(1000); downloadable test provider Assert.AreEqual(1,1); NUnit – Doesn’t support async,} downloadable test providerExecution Time1 sec
    18. 18. Metro and WinRThttp://blogs.msdn.com/b/windowsappdev/archive/2012/06/14/exposing-net-tasks-as-winrt-asynchronous-operations.aspxhttp://blogs.msdn.com/b/windowsappdev/archive/2012/03/20/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime.aspxhttp://blogs.msdn.com/b/windowsappdev/archive/2012/04/24/diving-deep-with-winrt-and-await.aspx Watch the other sessions on MetroIAsyncInfo App DevelopmentAll async methods in WinRTimplements this interface and 4 other Compiler MagicIAsyncAction IAsyncInfo has the awaitable patternIAsyncOperation<TResult> The C# and VB compiler will convertIAsyncActionWithProgress<TProgress> WinRT async methods to return TasksIAsyncOperationWithProgress<TResult,TProgress>
    19. 19. Choosing Sync vs Async SynchronousOperations are simple or short-running CPU bound operations Simplicity is more important Asynchronous I/O bound operations (DB, network, disk) Provide cancellation support Parallelism is more important
    20. 20. ADO.Net Tabular Data Stream ProtocolWorkerThread reader.NextResult() i/o “DONE” “DONE” Result Set Token Result Set Token reader.Next() i/o “ROW” “ROW” “ROW” Token Row Token Row Token Reader.IsDBNull() i/o Column Column Column Column Column Header Data Header Data Header pa ck et s Large Column e.g. varbinary(8000)
    21. 21. ADO.Net RecommendationsUse UseCommandBehavior.SequentialAccess NextResultAsync() and ReadAsync()Unless reading large columnsUseSynchronous column access UseIsDBNull, GetFieldValue<T> Streaming for massive columnsUnless reading large columns GetStream()IsDBNullAsync, GetTextReader()GetFieldValueAsync<T> GetXmlReader()
    22. 22. Resources• http://msdn.microsoft.com/en-US/async• VB.Net - http://blogs.msdn.com/b/lucian/• C# (implementation details) - https://msmvps.com/blogs/jon_skeet/archive /tags/Eduasync/default.aspx

    ×