19
Asynchronous Programming Filip Ekberg

Asynchronous programming from Xamarin Hakcday in Melbourne

Embed Size (px)

Citation preview

Asynchronous Programming

Filip Ekberg

I’m Filip Ekberg

Readify

@fekberg

Author. Blogger. Speaker. C# MVP. Xamarin MVP. Geek.

Senior Software Engineer @Invoice2go

Avoid Unreliable Applications!

• Don’t crash (doh!)• Don’t surprise the users• Show a loading indicator

12:38

@fekberg

Asynchronous Programming?

• Processing allowed before current execution is done, such as read/write to disk

• Asynchronous JavaScript (AJAX)

@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

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

Thank you,I’m Filip Ekberg

Readify

@fekberg

Author. Blogger. Speaker. C# MVP. Geek.