Book Image

iOS Development with Xamarin Cookbook

By : Dimitrios Tavlikos (USD)
Book Image

iOS Development with Xamarin Cookbook

By: Dimitrios Tavlikos (USD)

Overview of this book

Table of Contents (22 chapters)
iOS Development with Xamarin Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Running code in the background


In this recipe, we will learn how to execute code in the background, taking full advantage of iOS's multitasking feature.

Getting ready

Create a new Single View Application in Xamarin Studio and name it BackgroundCodeApp.

How to do it...

Perform the following steps:

  1. Enter the following code in the AppDelegate class:

    private int taskID;
    public override void DidEnterBackground (UIApplication application)
    {
      if (this.taskID == 0)
      {
        this.taskID = application.BeginBackgroundTask(() => {
          application.EndBackgroundTask(this.taskID);
          this.taskID = 0;
        });
        ThreadPool.QueueUserWorkItem(delegate {
          for (int i = 0; i < 60; i++)
          {
            Console.WriteLine("Task {0} - Current time {1}", this.taskID, DateTime.Now);
            Thread.Sleep(1000);
          }
          application.EndBackgroundTask(this.taskID);
          this.taskID = 0;
        });
      }
    }
    public override void WillEnterForeground (UIApplication application)
    {
      if (this.taskID != 0)
      {
     ...