www.dotnet.lv
Valdis Iljuconoks Technical Fellow, Software Architect Microsoft MVP Geta AS, Viiar Consulting valdis.iljuconoks@dotnet.lv http://dotnet.lv/blogs/vi @tech_fellow
C#
5.0
Async
concurrency & asynchrony
sequential concurrent parallel asynchronous
agenda predecessors awaiting tasks
predecessors
Asynchronous Programming Model (APM) Event-based Asynchronous Pattern (EAP)
C# 5.0 C# 4.0 Async C# 3.0 Dynamics Language C# 2.0 Integrated Generics Query C# 1.0 Component on a Managed Runtime
awaiting tasks
‘Task’ is representation of ongoing work
var var
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 operator cause 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 synchronously till 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 Iljuconoks Technical Fellow, Software Architect Microsoft MVP Geta AS, Viiar Consulting valdis.iljuconoks@dotnet.lv http://dotnet.lv/blogs/vi @tech_fellow
www.dotnet.lv

CSharp 5 Async