CSharp 5 Async

Preview:

Citation preview

www.dotnet.lv

Valdis IljuconoksTechnical Fellow, Software ArchitectMicrosoft MVP

Geta AS, Viiar Consultingvaldis.iljuconoks@dotnet.lvhttp://dotnet.lv/blogs/vi@tech_fellow

C#

5.0

Async

concurrency&

asynchrony

sequentialconcurrent

parallelasynchronous

agenda

predecessorsawaiting tasks

predecessors

Asynchronous Programming Model (APM)

Event-based Asynchronous Pattern (EAP)

C# 1.0Component on a Managed Runtime

C# 2.0Generics

C# 3.0Language Integrated Query

C# 4.0Dynamics

C# 5.0Async

awaiting tasks

‘Task’ is representation of ongoing work

var data = DownloadData(...);ProcessData(data);

var future = DownloadDataAsync(...); future.ContinueWith(data => ProcessData(data));

DownloadDataAsync ProcessData

STOP

ProcessDataDownloadData

async / await

similar to synchronous code

referred as async method

modifier (async) applied to

• a method• a lambda expression• an anonymous method

keyword (await) used in

• body of an immediately enclosing method

• lambda expression• anonymous method

await NOT used in

• synchronous function• query expression• catch or finally block• in lock statement• unsafe context

absence of an operatorcause a compiler warning

characteristics

Async methods are intended to be non-blocking operations

await expression does not block the current thread while the awaited task

is running

expression signs up the rest of the method as a continuation

and

returns control to the caller of the async method.

Method executes synchronouslytill first ‘await’.

Async methods don't require multithreading

async method doesn't run on its own thread

method runs on the current synchronization context.

Task based async pattern

Async method return types

• void• Task• Task<TResult>

async void FireAndForget(){ await t;}

FireAndForget();

async Task JustSignalCompletionAsync(){ return;}

await JustSignalCompletionAsync();

async Task<int> GetResultsAsync(){ return 5;}

var r = await GetResultsAsync();

Naming conventions

• By convention, the suffix "Async" is added

• Async methods that return void are discouraged

• Exceptions to the naming convention (e.g. event handlers)

?

Valdis IljuconoksTechnical Fellow, Software ArchitectMicrosoft MVP

Geta AS, Viiar Consultingvaldis.iljuconoks@dotnet.lvhttp://dotnet.lv/blogs/vi@tech_fellow

www.dotnet.lv