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; } }
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
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