Your SlideShare is downloading. ×
Deceptive simplicity of async and awaitWIN387Andrei Marukovichlunarfrog.com@amarukovich
Looks familiar?Deceptive simplicity of async and await
• Application errors• Using the UI thread for performing long operationsUI unresponsivenessDeceptive simplicity of async a...
Deceptive simplicity of async and awaitSynchronous methodprivate void ButtonClick(object sender, EventArgs e){WebClient cl...
Deceptive simplicity of async and awaitAsynchronous methodprivate async void ButtonClick(object sender, EventArgs e){WebCl...
Deceptive simplicity of async and awaitAsynchronous methodprivate async void ButtonClick(object sender, EventArgs e){WebCl...
Every API which might take more than 50msshould be asyncWinRTDeceptive simplicity of async and await
Deceptive simplicity of async and awaitDemoWinRT and async
Deep diveDeceptive simplicity of async and awaitstatic void Main(string[] args){DoSomething();}static void DoSomething(){/...
Deep diveDeceptive simplicity of async and await
State machineDeceptive simplicity of async and awaitstruct DoSomethingStruct : IAsyncStateMachine{// Argument and local va...
MoveNext()Deceptive simplicity of async and awaitvoid MoveNext() {try {switch(_state) {// modified method body}}catch (Exc...
Async function transformationDeceptive simplicity of async and awaitstatic Task DoSomething(){var stateMachine = new DoSom...
Using awaitDeceptive simplicity of async and awaitawait DoSomething();Task task = DoSomething();INotifyCompletion awaiter ...
Bringing it all togetherasync Task Method1(){await Method2();}async Task Method2(){await _file.CopyAsync(_folder, _name);}
Bringing it all togetherMethod1Method2TaskCopyAsyncCopyTask Method2Method1
Defining async methodsasync Task Method1(){}async Task<StorageFolder> Method2(){return ApplicationData.Current.LocalFolder...
Avoid async void as much as possibleDeceptive simplicity of async and await
Demoasync void and error handlingDeceptive simplicity of async and await
async lambdasobj.Handle( async () => { await Task.Delay(1000); } );Deceptive simplicity of async and awaitvoid Handle(Func...
DemoMore async in WinRTDeceptive simplicity of async and await
Constrains• Cannot use await inside constructor and property accessor• Cannot use await inside catch and finally• Cannot u...
What to take away• async/await are not magic• Always await your async operations• async void methods are only suited for U...
Next steps• Parallel Programming team blog http://bit.ly/pfxteam• Deeper into Async and Await, Kathleen Dollard ARC319• ...
Upcoming SlideShare
Loading in...5
×

Deceptive simplicity of async and await

1,458

Published on

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.

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,458
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Deceptive simplicity of async and await"

  1. 1. Deceptive simplicity of async and awaitWIN387Andrei Marukovichlunarfrog.com@amarukovich
  2. 2. Looks familiar?Deceptive simplicity of async and await
  3. 3. • Application errors• Using the UI thread for performing long operationsUI unresponsivenessDeceptive simplicity of async and await
  4. 4. Deceptive simplicity of async and awaitSynchronous methodprivate void ButtonClick(object sender, EventArgs e){WebClient client = new WebClient();var imageData = client.DownloadData(“http://image-url”);pictureBox.Image = Image.FromStream(new MemoryStream(imageData));}
  5. 5. Deceptive simplicity of async and awaitAsynchronous methodprivate async void ButtonClick(object sender, EventArgs e){WebClient client = new WebClient();var imageData = await client.DownloadDataTaskAsync(“http://image-url”);pictureBox.Image = Image.FromStream(new MemoryStream(imageData));}
  6. 6. Deceptive simplicity of async and awaitAsynchronous methodprivate async void ButtonClick(object sender, EventArgs e){WebClient client = new WebClient();var imageData = await client.DownloadDataTaskAsync(“http://image-url”);pictureBox.Image = Image.FromStream(new MemoryStream(imageData));var strData = await client.DownloadStringTaskAsync(“http://str-url”);// …}
  7. 7. Every API which might take more than 50msshould be asyncWinRTDeceptive simplicity of async and await
  8. 8. Deceptive simplicity of async and awaitDemoWinRT and async
  9. 9. Deep diveDeceptive simplicity of async and awaitstatic void Main(string[] args){DoSomething();}static void DoSomething(){// method body}static void Main(string[] args){DoSomething();}async static Task DoSomething(){// method body}
  10. 10. Deep diveDeceptive simplicity of async and await
  11. 11. State machineDeceptive simplicity of async and awaitstruct DoSomethingStruct : IAsyncStateMachine{// Argument and local variablespublic Int32 x;// Compiler-generated variablespublic Int32 _state;public AsyncTaskMethodBuilder _builder;void MoveNext() { … }}
  12. 12. MoveNext()Deceptive simplicity of async and awaitvoid MoveNext() {try {switch(_state) {// modified method body}}catch (Exception exception) {_builder.SetException(exception);return;}_builder.SetResult();}
  13. 13. Async function transformationDeceptive simplicity of async and awaitstatic Task DoSomething(){var stateMachine = new DoSomethingStruct();stateMachine._builder = AsyncTaskMethodBuilder.Create();stateMachine._state = -1;stateMachine._builder.Start(stateMachine);return stateMachine._builder.Task;}
  14. 14. Using awaitDeceptive simplicity of async and awaitawait DoSomething();Task task = DoSomething();INotifyCompletion awaiter = task.GetAwaiter();if (!awaiter.IsCompleted) {awaiter.OnCompleted(continue_delegate)}
  15. 15. Bringing it all togetherasync Task Method1(){await Method2();}async Task Method2(){await _file.CopyAsync(_folder, _name);}
  16. 16. Bringing it all togetherMethod1Method2TaskCopyAsyncCopyTask Method2Method1
  17. 17. Defining async methodsasync Task Method1(){}async Task<StorageFolder> Method2(){return ApplicationData.Current.LocalFolder;}async void button1_Click(object sender, EventArgs e){}
  18. 18. Avoid async void as much as possibleDeceptive simplicity of async and await
  19. 19. Demoasync void and error handlingDeceptive simplicity of async and await
  20. 20. async lambdasobj.Handle( async () => { await Task.Delay(1000); } );Deceptive simplicity of async and awaitvoid Handle(Func<Task> action);Func<Task> f = async () => { await Task.Delay(1000); }void Handle(Action action);Action a = async () => { await Task.Delay(1000); }IL: AsyncTaskMethodBuilderIL: AsyncVoidMethodBuilder
  21. 21. DemoMore async in WinRTDeceptive simplicity of async and await
  22. 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. 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. 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

×