Date post: | 07-Aug-2015 |
Category: |
Technology |
Upload: | filip-ekberg |
View: | 659 times |
Download: | 0 times |
No More DeadlocksFilip Ekberg
I’m Filip Ekberg
Readify
@fekberg
Author. Blogger. Speaker. .NET MVP. Xamarin MVP. Geek.
Senior Software Engineer @
Asynchronous Programming?
• Processing allowed before current execution is done, such as read/write to disk
• Asynchronous JavaScript (AJAX)
@fekberg
Why are we talking about this now?• Not a new concept• Becoming more and more common
@fekberg
• Web Apps• Mobile Apps• Desktop Apps
Avoid Unreliable Applications!
• Don’t crash (doh!)• Don’t surprise the users• Show a loading indicator
12:38
@fekberg
Not the same as Parallel Programming
@fekberg
From Sync to Async
@fekberg
From Blocking to Non-Blocking
• Free the main/UI thread quickly• Don’t force a block because async is
difficult
@fekberg
Task Parallel Library (TPL)
Simplify the work of writing concurrent and asynchronous code
@fekberg
Refresh my mind!
@fekberg
var task = Task.Run(() => {
Thread.Sleep(2000);
return "Hello World!";});
task.ContinueWith((completedTask) => { Dispatcher.Invoke(() => MyButton.Content = completedTask.Result);});
Continuation not on UI Thread!
Invoke on the UI Thread!
Easy Deadlocking
@fekberg
Task.Delay(1).ContinueWith((t) => { Dispatcher.Invoke(() => { });}).Wait();
Block the UI Thread!Invoke on the UI Thread!
Introducing Async and Await
@fekberg
New Contextual Keywords
Async and Await were introduced in .NET 4.5
• Hides a lot of complexity behind the scenes
• Makes code more readable• Makes code more fragile
@fekberg
Does this apply to ASP.NET?
• Yes!• But.. The caller will know no difference
@fekberg
What about Xamarin?
• Scheduling might differ per platform• Potentially easier to deadlock!
@fekberg
Demo
Using Async and Await
@fekberg
Behind the Scenes
@fekberg
Example
@fekberg
private async Task RunAsync(){ var x = 10;
await Task.Delay(2000);
Debug.WriteLine(x);}
What about RunAsync’s method body?
@fekberg
private Task RunAsync(){ <RunAsync>d__1 stateMachine = new <RunAsync>d__1 { <>t__builder = AsyncTaskMethodBuilder.Create(), <>1__state = -1 }; stateMachine.<>t__builder.Start<<RunAsync>d__1>(ref stateMachine); return stateMachine.<>t__builder.Task;}
Demo
Deadlock all the things!
@fekberg
Considerations
• Don’t mark void methods as asynchronous methods
• Tasks swallow Exceptions!• Wait() this is an easy path to
deadlocking• Follow the naming convention
MyMethodAsync• Don’t lie by wrapping
synchronous/blocking code in async methods
• The continuation is on the calling thread!
@fekberg
Questions?
Readify
@fekberg
Thank you,I’m Filip Ekberg
Readify
@fekberg
Author. Blogger. Speaker. .NET MVP. Xamarin MVP. Geek.
Senior Software Engineer @