Asynchronous tasks
All apps need to perform tasks that may take longer than a few milliseconds. If a task blocks the UI thread for longer than a few seconds, Android will terminate it, crashing the application.
How to do it...
If we want to do work in the background, we use a new thread. To do this, we make use of the Task Parallel Library (TPL) and the async
/await
keywords:
The first thing that is needed is the method that we wish to execute:
public async Task DoWorkAsync() { await Task.Run(() => { // some long running task }); }
We then invoke it like a normal method, but just with the
await
keyword:await DoWorkAsync();
We can also attach it to an event:
doWork.Click += async (sender, args) => { await DoWorkAsync(); }
We can also override the
void
methods by simply inserting theasync
keyword before the return type:protected override async void OnCreate(Bundle bundle) { base.OnCreate(bundle); await DoWorkAsync(); }
If the method needs to return a value, we use
Task<>
:...