Upload
frank-washington
View
215
Download
3
Embed Size (px)
Citation preview
Easy Asynchrony with C#: No More Callbacks!
Mads TorgersenProgram Manager3-011
The future is the future
Responsiveness and scalability
Async is becoming the norm
Futures: Modern abstractions
Details: Different but similar
Windows Runtime
Async
.NET Asyn
c
Synchronous versus asynchronous
var data = DownloadData(...);ProcessData(data);
var future = DownloadDataAsync(...); future.ContinueWith(data => ProcessData(data));
DownloadDataAsync ProcessData
STOP
ProcessDataDownloadData
Synchronous versus asynchronous
var data = DownloadData(...);ProcessData(data);
DownloadDataAsync ProcessData
STOP
ProcessDataDownloadData
STOP
var future = DownloadDataAsync(...); future.ContinueWith(data => ProcessData(data));
C# and Visual Basic let you doasynchronous programmingwithout callbacks
demo
Using await with the Windows Runtime
asyncmakes your method asynchronous
await makes the rest of your method a callback
Awaitables
TaskTask<TResult>
Returned from asyncC# and Visual Basic APIs
Already running
await directlyCan await multiple timesStore and await later
IAsyncActionIAsyncOperation<TResult>
Returned from asyncWindows Runtime APIs
Already running
await directlyCan await multiple timesStore and await laterAsTask to get a Task
Task-returning verus void-returning
async Task FooAsync(…);
Can be awaited“Give back control”Delegate asynchronous work
Use for helper methodsUse for library methods
async void Foo_Click(…);
Cannot be awaited“Fire and forget” Start separate independent flow
Use for event handlersUse to override void methods
demo
Coordinating tasks
Task lets you coordinate activities
Task helpers
• Yielding controlawait Task.Delay(5000);await Task.Yield();
• Background runningvar result = await Task.Run(() => { … work … });
• Parallel compositionTask first = await Task.WhenAny(task1, task2);var results = await Task.WhenAll(task1, task2);
demo
Cancellation
Cancellation and Progress
Pass CancellationToken to send cancellationPass IProgress to receive progress updates
await FooAsync(…, cancel, progress);await FooAsync(…).AsTask(cancel, progress);
No more callbacks!
© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.