How to handle a cancelled background task
Language: HTML | XAML

How to handle a cancelled background task (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Learn how to make a background task that recognizes cancellation requests and stops work, reporting the cancellation to the app using the background task instance and persistent storage.

Note  For Windows Phone Store apps, if the device becomes low on memory, background tasks may be terminated without any warning and without raising the OnCanceled event. This helps to ensure the user experience of the app in the foreground. Your background task should be designed to handle this scenario.

What you need to know

Technologies

Prerequisites

Instructions

Step 1: Use an event handler to recognize cancellation requests

Write a method to handle the cancellation event.

  1. Create a method named OnCanceled that has the following footprint. This method is the entry point called by the Windows Runtime whenever a cancellation request is made against your background task.

    The OnCanceled function needs to have the following footprint:

    
    
    function onCanceled(cancelSender, cancelReason)
    {
        // TODO: Add code to notify the background task that it is cancelled.
    }
    
    
  2. Add a variable called cancel to the background task. This will be used to indicate when a cancellation request has been received.

    For example, put this line of code at the top of your IBackgroundTask class, along with other variable definitions:

    
    var cancel = false;
    
    
  3. In the OnCanceled method you created in step 1, set cancel to true.

    The full background task sample OnCanceled method sets cancel to true:

    
    function onCanceled(cancelSender, cancelReason) {
        cancel = true;
    }
    
    
  4. Register the OnCanceled method with the "canceled" event listener before starting work in the background task.

    For example, use the following line of code:

    
    
    backgroundTaskInstance.addEventListener("canceled", onCanceled);
    
    

Step 2: Handle cancellation and exit

The Run method needs to monitor the cancel variable, so it can quit when the variable is set to true.

  1. Modify the code of your background task class to stop work if cancel is set to true.

    The background task sample includes a check that stops the periodic timer callback if the background task is canceled:

    
    
    if (!cancel) {
        // Do work.
    }
    else
    {
        // Cancel.
    }
    
    
  2. After work has stopped, clean up by setting the background task instance's succeeded property to false, and record that the task was cancelled. The call close() to exit the function.

    The background task sample records status in LocalSettings:

    
    
    if ((_cancelRequested == false) && (_progress < 100))
    {
        // See the background task sample for this code.
    }
    else
    {
        //
        // If the cancellation handler indicated that the task was canceled, stop the background task.
        //
        console.log("Background " + backgroundTaskInstance.task.name + " Canceled");
        backgroundTaskInstance.succeeded = false;
    
        key = backgroundTaskInstance.task.taskId.toString();
        settings.values[key] = "Canceled";
    
        close();
    }
    
    

Remarks

You can download the background task sample to see these code examples in the context of methods.

For illustrative purposes, the sample code above shows only portions of the background task (and callback timer) from the background task sample.

Run method example

The complete JavaScript background task from the background task sample is shown below for context:


//
// A JavaScript background task runs a specified JavaScript file.
//
(function () {
    "use strict";

    //
    // The background task instance's activation parameters are available via Windows.UI.WebUI.WebUIBackgroundTaskInstance.current
    //
    var cancel = false,
        progress = 0,
        backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;

    console.log("Background " + backgroundTaskInstance.task.name + " Starting...");

    //
    // Associate a cancellation handler with the background task.
    //
    function onCanceled(cancelSender, cancelReason) {
        cancel = true;
    }
    backgroundTaskInstance.addEventListener("canceled", onCanceled);

    //
    // This function is set to run every 1000 milliseconds ten times and perform background task activity.
    //
    function onTimer() {
        var key = null,
            settings = Windows.Storage.ApplicationData.current.localSettings;

        if (!cancel) {
            if (progress < 100) {
                //
                // Simulate work being done.
                //
                setTimeout(onTimer, 1000);

                //
                // Indicate progress to the foreground application.
                //
                backgroundTaskInstance.progress = progress;
                progress += 10;
            } else {
                //
                // Use the succeeded property to indicate that this background task completed successfully.
                //
                backgroundTaskInstance.succeeded = true;
                backgroundTaskInstance.progress = progress;
                console.log("Background " + backgroundTaskInstance.task.name + " Completed");

                //
                // Write to localSettings to indicate that this background task completed.
                //
                key = backgroundTaskInstance.task.name;
                settings.values[key] = "Completed";

                //
                // A JavaScript background task must call close when it is done.
                //
                close();
            }
        } else {
            //
            // If the cancellation handler indicated that the task was canceled, stop the background task.
            //
            console.log("Background " + backgroundTaskInstance.task.name + " Canceled");
            backgroundTaskInstance.succeeded = false;

            key = backgroundTaskInstance.task.taskId.toString();
            settings.values[key] = "Canceled";

            close();
        }
    }

    //
    // Start the timer function to simulate background task work.
    //
    setTimeout(onTimer, 1000);
})();

Related topics

Quickstart: Create and register a background task
How to register a background task
How to debug a background task
Supporting your app with background tasks
How to get a list of pending background tasks
How to monitor background task progress and completion
How to declare background tasks in the application manifest
Guidelines and checklists for background tasks

 

 

Show:
© 2017 Microsoft