O'Reilly logo

Xamarin Mobile Development for Android Cookbook by Matthew Leibowitz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required