Ddd melbourne 2011 C# async ctp

25
Introducing C# Async CTP Pratik Khasnabis DDD Melbourne 2011

description

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

Transcript of Ddd melbourne 2011 C# async ctp

Page 1: Ddd melbourne 2011  C# async ctp

Introducing C# Async CTPPratik Khasnabis

DDD Melbourne 2011

Page 2: Ddd melbourne 2011  C# async ctp

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.

Page 3: Ddd melbourne 2011  C# async ctp

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

Page 4: Ddd melbourne 2011  C# async ctp

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

Page 5: Ddd melbourne 2011  C# async ctp

Why Async ?

Page 6: Ddd melbourne 2011  C# async ctp

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.

Page 7: Ddd melbourne 2011  C# async ctp

• 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 ?

Page 8: Ddd melbourne 2011  C# async ctp

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

Page 9: Ddd melbourne 2011  C# async ctp

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

Page 10: Ddd melbourne 2011  C# async ctp

Demo

Page 11: Ddd melbourne 2011  C# async ctp

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

Page 12: Ddd melbourne 2011  C# async ctp

Demo

Page 13: Ddd melbourne 2011  C# async ctp

Sync => Async

Add reference to the Async CTP Library

Page 14: Ddd melbourne 2011  C# async ctp

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

Page 15: Ddd melbourne 2011  C# async ctp

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

Page 16: Ddd melbourne 2011  C# async ctp

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

Page 17: Ddd melbourne 2011  C# async ctp

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

Page 18: Ddd melbourne 2011  C# async ctp

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

}

Page 19: Ddd melbourne 2011  C# async ctp

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

Page 20: Ddd melbourne 2011  C# async ctp

Asynchronous ≠ Concurrent

DownloadDataAsync

ParseResponse

DisplayPhotos

UI Thread

UI Messages

Just One

Thread !!

Hang

Page 21: Ddd melbourne 2011  C# async ctp

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.

Page 22: Ddd melbourne 2011  C# async ctp

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

Page 23: Ddd melbourne 2011  C# async ctp

TaskEx

• TaskEx.Delay()• TaskEx.Run()• TaskEx.WhenAll()• TaskEx.WhenAny()• TaskEx.Yield()

Page 25: Ddd melbourne 2011  C# async ctp

Questions