Async ProgrammingWhy do we need async?• Responsive UI.• Leverage Computing Power.• Better Utilization of Resources.• Better user experience. What is expected from Async programming patterns? • Transparent Remote operations • Easy to code • Cancellations, Timeouts, Preserving threads during blocking awaits etc.
Pre matured ways of async programming. Recommended Async Programming Concepts • Don’t wait for the response. • Return immediately after issuing a async request • Let the response call you back. Earlier ways • IAsyncResult Pattern Ex: BeginRead, EndRead • Event based Asynchronous pattern Sync Async
Pre matured ways of async programming. What went wrong? • Disruptive Program Structure • Error prone • Heavy weight • Difficult to design and write
What is Async CTP?• A new language feature• New framework patternWhat do you need to start working onAsync CTP• Visual Studio 2011 Beta• Visual Studio 2010 SP1 with Async CTPDownload from:http://www.microsoft.com/download/en/details.aspx?id=9983
Task and Task<T> • A Task is a representation of ongoing work • Available in .NET 4 • Task returns nothing, Task<T> returns a result of type T. • Normal tasks - Independent of Thread. • Async tasks run on same thread. • Propagate Exceptions
‘async’ modifier • Indicates Asynchrony • Can be used for methods or Events or Methods or Lambdas • Out and ref are not allowed. • Analogous to ‘yield’
‘await’ keyword • Await - Prepend to a method which can return Task, Task<T> • Everything that continues is compiled asynchronously • ‘Async’ Runs synchronously until first ‘await’.
Task basedProgramming TASK BASED ASYNC PATTERN
Task based async pattern Async UI Thread Caller Method Task/Task<T> Create Task & Check for callback Wait for ‘await’ Load the Context Capture Context continue Sign up a call back.