c# 5 async-await (for eastbay.net)

29
Craig Dunn Developer Evangelist Xamarin [email protected] @conceptdev C# async await

Upload: craig-dunn

Post on 10-May-2015

1.886 views

Category:

Technology


0 download

DESCRIPTION

.NET FUNdamentals presentation for EastBay.NET User Group. Quick overview of the new async-await keywords in C# 5

TRANSCRIPT

Page 2: C# 5 async-await (for EastBay.NET)

Mobile Apps

• Need responsive user interfaces• App features are o!en dependent on:

network accessdatabase functionality or I/Ocomplex processing on mobile CPUsstuff that takes some time

• You want to run these on a different thread to keep the UI responsive... they should be ASYNCHRONOUS!

Fast!

Long running tasks!

Threads!

All

Page 3: C# 5 async-await (for EastBay.NET)

DEMODEMO1) Download Html string2) Download Jpeg image3) Save to Storage4) Return Html length

Page 4: C# 5 async-await (for EastBay.NET)

Old-style callbacks

1) Download Html string2) Download Jpeg image3) Save to Photo Album

5) Error Handling4) Return Html length

6) InvokeOnMainThread

Callback Hell

Page 5: C# 5 async-await (for EastBay.NET)

1) Download Html string2) Download Jpeg image3) Save to Photo Album

5) Error Handling4) Return Html length

6) InvokeOnMainThread

Callback Hell

Old-style callbacks

Page 6: C# 5 async-await (for EastBay.NET)

Old-style callbacks

• Spaghetti code:

Callbacks are the new “GOTO”Control flow jumps around in ways that are difficult to read & understand from the sourceError handling is difficult to implement, required in many different placesChanges in the chain can have unintended consequences

http://tirania.org/blog/archive/2013/Aug-15.html

Page 7: C# 5 async-await (for EastBay.NET)

What is “async”?

• Tasks running outside of the main program flow• Code runs on another thread, so the UI doesn’t block/freeze• Completion runs on the calling thread, so if you started on the

UI that’s where you’ll be a!er the async task is complete

• async and await syntax in C# 5 takes Task support to the next level!

Frameworks need to support it on long running tasks

Task Parallel Library (TPL) has been around a while

Page 8: C# 5 async-await (for EastBay.NET)

.NET BCL APIs

• Lots of .NET APIs support async; for example:HttpClient.GetStringAsync()HttpClient.PostAsync()FileStream.ReadAsync()FileStream.CopyToAsync()

• and many more...

Windows Store and Phone appsonly have async APIs

Page 9: C# 5 async-await (for EastBay.NET)

Xamarin.iOS

• updated iOS APIs to be async; some examples:ALAssetsLibrary.WriteImageToSavedPhotosAlbumAsync()ALAsset.SetImageDataAsync()SKStoreProductViewController.LoadProductAsync()CLGeocoder.GeocodeAddress()NSUrlConnection.SendRequestAsync()

and many more... 174 async iOS native APIs

Page 10: C# 5 async-await (for EastBay.NET)

Xamarin.Android

• updated Android APIs to be async; some examples:Android.Net.Http.AndroidHttpClient.ExecuteAsync()Android.Bluetooth.BluetoothServerSocket.AcceptAsync()Android.Graphics.BitmapFactory.DecodeFileAsync()Android.Locations.Geocoder.GetFromLocationAsync()Java.IO.File.ListAsync()

and many more... 337 async Android native APIs

Page 11: C# 5 async-await (for EastBay.NET)

Xamarin APIs

• Xamarin.Mobile Geolocator.GetPositionAsync()Contact.SaveThumbnailAsync()

• Xamarin.Auth

FormAuthenticator.SignInAsync()Request.GetResponseAsync(cancellationToken)

• and many more...Xamarin cross-platform libraries

Page 12: C# 5 async-await (for EastBay.NET)

Xamarin Component Store

• Many components already offer async APIs, eg. Parse!

Powerful, easy to use componentshttp://components.xamarin.com

Page 13: C# 5 async-await (for EastBay.NET)

USING ASYNCasync, await, cancellation and error handling

Page 14: C# 5 async-await (for EastBay.NET)

Comparison

1) Download Html string2) Download Jpeg image3) Save to Photo Album

5) Error Handling4) Return Html length

6) InvokeOnMainThread

Callback Hell

Page 15: C# 5 async-await (for EastBay.NET)

Comparison

1) Download Html string2) Download Jpeg image3) Save to Photo Album

5) Error Handling4) Return Html length

6) InvokeOnMainThread

Callback Hell

Page 16: C# 5 async-await (for EastBay.NET)

1) Download Html string2) Download Jpeg image3) Save to Photo Album

5) Error Handling4) Return Html length

Comparison

Async-ified

6) InvokeOnMainThread

Page 17: C# 5 async-await (for EastBay.NET)

1) Download Html string2) Download Jpeg image3) Save to Photo Album

5) Error Handling4) Return Html length

Comparison

6) InvokeOnMainThreadone place

not required

Async-ified

Page 18: C# 5 async-await (for EastBay.NET)

Comparison

1) Download Html string2) Download Jpeg image3) Save to Photo Album

5) Error Handling4) Return Html length

6) InvokeOnMainThread

old new!

Page 20: C# 5 async-await (for EastBay.NET)

Compiler Magic• async keyword informs the compiler that this method needs to be

“munged” (my term)• await keyword indicates a suspension point where a callback

needs to be generated, along with error handling• Continuations are generated a!er each suspension point• Error handling (support for enclosing try-catch) is taken care of

• All you need to remember is async and awaitand use Tasks

Page 21: C# 5 async-await (for EastBay.NET)

How to use: async?• async modifier on methods, lambdas and anonymous methods

use Async suffix, eg LoadAsync, SendAsyncreturn Task or Task<T> preferably

- Task for methods that don’t return a value

- Task<T> to return a value

- void for event handlers only!

void for event handlers

Page 22: C# 5 async-await (for EastBay.NET)

How to use: await?• await keyword on awaitable objects (Tasks)

only within an async contextmarks a suspension point - control is returned to callercan’t be used in catch or finally blocksTask, Task<T> or a custom type

get a reference to the Task first

... or just await

Page 23: C# 5 async-await (for EastBay.NET)

How to use: error handling?• async Task or Task<T>

Returned Task State == FaultedException re-thrown when task is awaited

• async void methods (event handlers)Exception is thrown on the current synchronization context and the app will crash...

Page 24: C# 5 async-await (for EastBay.NET)

• Cancellation is optionalprovide another Async method, usually an overload, that takes a CancellationToken parametercaller uses the tokenasync tasks complete with Faulted state (time for this to happen isn’t guaranteed)Cancellation.None means it won’t be cancelled by the caller

How to use: cancellation?

Page 25: C# 5 async-await (for EastBay.NET)

• Progress reporting is optionalprovide another Async overload with an IProgress<T> parameterbasic Progress<T> implementation can be usedexposes EventHandler<T> ProgressChanged

How to use: progress reporting?

send events to track progress

Page 26: C# 5 async-await (for EastBay.NET)

BONUS: Combinators• Wait on multiple tasks

Task.WhenAll (IEnumerable<Task>)

- requires all the tasks to be completedTask.WhenAny(IEnumerable<Task>)

- returns when any of the tasks completes

this kind of loop fine for small numbersof Tasks

Page 27: C# 5 async-await (for EastBay.NET)

WARNING: Await, and UI, and deadlocks

http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx

Page 28: C# 5 async-await (for EastBay.NET)

Don’t await... give it a try• Available in .NET 4.5 for Windows Store apps, Windows 8,

Windows Phone, etc.

• Also available programming in C# iOS & Android using Xamarin!

xamarin.com/download