2. Mobile Apps
ā¢ Need responsive user interfaces
ā¢ App features are o!en dependent on:
network access
database functionality or I/O
complex processing on mobile CPUs
stuļ¬ that takes some time
ā¢ You want to run these on a diļ¬erent thread to keep the UI
responsive... they should be ASYNCHRONOUS!
Fast!
Long running tasks!
Threads!
All
4. Old-style
callbacks
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
5. 1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
Old-style
callbacks
6. Old-style callbacks
ā¢ Spaghetti code:
Callbacks are the new āGOTOā
Control flow jumps around in ways that are diļ¬icult to read
& understand from the source
Error handling is diļ¬icult to implement, required in many
diļ¬erent places
Changes in the chain can have unintended consequences
http://tirania.org/blog/archive/2013/Aug-15.html
7. 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
8. .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 apps
only have async APIs
9. 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
10. 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
14. Comparison
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
15. Comparison
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
Callback Hell
16. 1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
Comparison
Async-ified
6) InvokeOnMainThread
17. 1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
Comparison
6) InvokeOnMainThread
one place
not required
Async-ified
18. Comparison
1) Download Html string
2) Download Jpeg image
3) Save to Photo Album
5) Error Handling
4) Return Html length
6) InvokeOnMainThread
old new!
20. 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 await
and use Tasks
21. How to use: async?
ā¢ async modifier on methods, lambdas and anonymous methods
use Async suļ¬ix, eg LoadAsync, SendAsync
return 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
22. How to use: await?
ā¢ await keyword on awaitable objects (Tasks)
only within an async context
marks a suspension point - control is returned to caller
canāt be used in catch or finally blocks
Task, Task<T> or a custom type
get a reference
to the Task first
... or just await
23. How to use: error handling?
ā¢ async Task or Task<T>
Returned Task State == Faulted
Exception re-thrown when task is awaited
ā¢ async void methods (event handlers)
Exception is thrown on the current synchronization context
and the app will crash...
24. ā¢ Cancellation is optional
provide another Async method, usually an overload, that
takes a CancellationToken parameter
caller uses the token
async 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?
25. ā¢ Progress reporting is optional
provide another Async overload with an IProgress<T>
parameter
basic Progress<T> implementation can be used
exposes EventHandler<T> ProgressChanged
How to use: progress reporting?
send events to
track progress
26. BONUS: Combinators
ā¢ Wait on multiple tasks
Task.WhenAll (IEnumerable<Task>)
- requires all the tasks to be completed
Task.WhenAny(IEnumerable<Task>)
- returns when any of the tasks completes
this kind of
loop fine for
small numbers
of Tasks
27. WARNING: Await, and UI, and deadlocks
http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx
28. 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