Xamarin with SQLite Telerik School Academy Xamarin apps for iOS, Android & WinPhone.
Asynchronous programming from Xamarin Hakcday in Melbourne
-
Upload
filip-ekberg -
Category
Technology
-
view
181 -
download
0
Transcript of Asynchronous programming from Xamarin Hakcday in Melbourne
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
From Blocking to Non-Blocking
• Free the main/UI thread quickly• Don’t force a block because async is
difficult
@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!
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
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;}
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