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:

  1. 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
      });
    }
  2. We then invoke it like a normal method, but just with the await keyword:
    await DoWorkAsync();
  3. We can also attach it to an event:
    doWork.Click += async (sender, args) => {
      await DoWorkAsync();
    }
  4. We can also override the void

Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.