Introducing C# Async CTP<br />Pratik Khasnabis<br />DDD Melbourne 2011<br />
About Me<br />Lead .Net Developer BUPA Australia<br />Pratik Khasnabis<br />Work For<br />Tweet as<br />C#<br />Disclaimer...
What you will learn today ?<br />Why is asynchronous programming important<br />The Task-Based Asynchronous Pattern (TAP)<...
What you will NOT learn today ?<br />The implementation details on how the pattern works<br />Other features introduced in...
Why Async ?<br />
Why Asynchronous ?<br />Responsive UI<br />Waiting on I/O or long computation will stop message processing and hang the ap...
Threads are not the answer<br />Thread creation is expensive<br />Each managed thread takes 1MB of stack space<br />Contex...
Asynchronous Programming Model<br />public class Stream<br />{<br />public intRead(byte[] buffer, intoffset, intcount);<br...
Event-Based Asynchronous Pattern<br />public class Stream<br />{<br />public void ReadAsync(byte[] buffer, intoffset, intc...
Demo<br />
C# and VB.NetAsync CTP<br />First introduced in PDC 2010 and the refresh in MIX 2011 (VS 2010 SP1)<br />Introduces async a...
Demo<br />
Sync => Async<br />Add reference to the Async CTP Library<br />
Sync => Async<br />Add asyncmodifier to the return types<br />Change return type to Task<TResult><br />Add Async suffix to...
C# Async Features<br />Asynchronous methods (and lambdas, and anonymous delegates) are a new feature in C#<br />Asynchrono...
C# AsyncFeatures, contd.<br />Asynchronous methods can have small synchronous statements<br />Asynchronous methods should ...
C# Async Features, end.<br />Asynchronous methods with void return type are fire-and-forget<br />Cannot be awaited on<br /...
Task-Based Async Pattern<br />public class Stream<br />{<br />public Task<int> ReadAsync(byte[] buffer, intoffset, intcoun...
Tracing the control flow<br />Caller<br />Void Async Method<br />Task AsyncMethod<br />Awaitable<br />UI<br />thread<br />...
Asynchronous ≠ Concurrent<br />Hang<br />UI Thread<br />UI Messages<br />DisplayPhotos<br />Just One Thread !!<br />Downlo...
Asynchronous ≠ Concurrent <br />Asynchronous operations can share a single thread for multiple control flows<br />The UI a...
Implementation<br />The type of the expression awaited is based on a pattern satisfied by Task and Task<T><br />GetAwaiter...
Task-Based Async Pattern<br />TAP methods return Task or Task<TResult><br />TAP methods ends with an “Async” suffix by con...
TaskEx<br />TaskEx.Delay()<br />TaskEx.Run()<br />TaskEx.WhenAll()<br />TaskEx.WhenAny()<br />TaskEx.Yield()<br />
Resources<br />CTP - http://msdn.microsoft.com/en-us/vstudio/gg316360<br />C# - http://blogs.msdn.com/b/ericlippert/<br />...
Upcoming SlideShare
Loading in …5
×

Ddd melbourne 2011 C# async ctp

1,608
-1

Published on

The slides are from DDD Melbourne 2011 session "Introducing C# Async CTP" by Pratik Khasnabis

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,608
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
22
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Ddd melbourne 2011 C# async ctp

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

×