Introducing C# Async CTPPratik Khasnabis
DDD Melbourne 2011
About Me
Pratik Khasnabis Lead .Net Developer BUPA Australia
@softveda
C#
Solution Design
WCF & SOA
Work For
Tweet as
Disclaimer:The opinions and viewpoints expressed in this presentation are my own and are not necessarily those of my employer, BUPA Australia.
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 Modelpublic class Stream{ public int Read(byte[] buffer, int offset,
int count); public IAsyncResult BeginRead(byte[] buffer,
int offset, int count, AsyncCallback callback, object state);
public int EndRead(IAsyncResult asyncResult);}
Event-Based Asynchronous Patternpublic class Stream{ public void ReadAsync(byte[] buffer, int offset,
int count); public event ReadCompletedEventHandler
ReadCompleted;}public delegate void
ReadCompletedEventHandler(object sender, ReadCompletedEventArgs eventArgs);
public class ReadCompletedEventArgs : AsyncCompletedEventArgs
{ public int Result { get; }}
Demo
C# and VB.Net Async 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 async modifier 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 async modifier 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# Async Features, 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 Patternpublic class Stream{ public Task<int> ReadAsync(byte[] buffer, int
offset, int count);
public Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken, IProgress<T> progress);
}
Tracing the control flowCaller Void Async Method Task Async Method Awaitable
async voidLoadPhotosAsync(string tag){ …var photosTask = GetPhotosAsync(tag, page);
var photos = await photosTask;
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;
}
IOCPthread
UIthread
I/O Task
UI Task C1
C2
C1C1
C2
1
1
2
2
Button Click
DownloadDone
Asynchronous ≠ Concurrent
DownloadDataAsync
ParseResponse
DisplayPhotos
UI Thread
UI Messages
Just One
Thread !!
Hang
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.
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/
VB.Net - http://blogs.msdn.com/b/lucian/
Jon Skeet (implementation details) https://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx
Questions
Top Related