Understanding of asynchronous model is an essential knowledge for development of quality Windows Store apps. This session dives deep into implementation details of async and await C# keywords and provides information about common pitfalls and mistakes of async pattern use and the ways to avoid them.
11. State machine
Deceptive simplicity of async and await
struct DoSomethingStruct : IAsyncStateMachine
{
// Argument and local variables
public Int32 x;
// Compiler-generated variables
public Int32 _state;
public AsyncTaskMethodBuilder _builder;
void MoveNext() { … }
}
12. MoveNext()
Deceptive simplicity of async and await
void MoveNext() {
try {
switch(_state) {
// modified method body
}
}
catch (Exception exception) {
_builder.SetException(exception);
return;
}
_builder.SetResult();
}
13. Async function transformation
Deceptive simplicity of async and await
static Task DoSomething()
{
var stateMachine = new DoSomethingStruct();
stateMachine._builder = AsyncTaskMethodBuilder.Create();
stateMachine._state = -1;
stateMachine._builder.Start(stateMachine);
return stateMachine._builder.Task;
}
14. Using await
Deceptive simplicity of async and await
await DoSomething();
Task task = DoSomething();
INotifyCompletion awaiter = task.GetAwaiter();
if (!awaiter.IsCompleted) {
awaiter.OnCompleted(continue_delegate)
}
15. Bringing it all together
async Task Method1()
{
await Method2();
}
async Task Method2()
{
await _file.CopyAsync(_folder, _name);
}
16. Bringing it all together
Method1
Method2
Task
CopyAsync
Copy
Task Method2
Method1
22. Constrains
• Cannot use await inside constructor and property accessor
• Cannot use await inside catch and finally
• Cannot use await inside lock block
• Cannot use await inside Main method
• An async method cannot have a ref or out parameters
23. What to take away
• async/await are not magic
• Always await your async operations
• async void methods are only suited for UI event handlers
• Be careful around async void and exceptions
• Be aware of deferral classes in WinRT
24. Next steps
• Parallel Programming team blog
http://bit.ly/pfxteam
• Deeper into Async and Await, Kathleen Dollard
ARC319
• Three Essential Tips for Async (video)
http://bit.ly/AsyncTips
• Async for .NET 4.0 and Windows Phone (NuGet)
http://bit.ly/AsyncNet4