Background task pollution

April 22, 2012 at 1:21 pm | Posted in HTML/JavaScript, Metro, Windows 8 | Leave a comment

I am developing a Metro HTML/JavaScript application which uses a background task to notify the user of updates to some data that is collected periodically. Initally, the background task simply read the data, did some filtering and sent a tile notification. This all seemed to be working well. When I added a toast notification; however, I began to see some strange behavior.

First, I noticed that when the background task fired based on a timer, that dozens of processes seemed to appear in the Visual Studio debugger. Second, I found that the toast was triggered multiple times for each interval. Of course, this continued even if the program was no longer running. It occurred after a reboot also.

My suspicion was that the background task was registered multiple times. My program was configured to register the background task every time it was launched. I assumed that the system would just overwrite the previous registration with the new one. It appears, though that each registration is added to a list of registrations even if they are identical. After numerous debug sessions, these registrations were adding up. I was polluting the background task manager.

The programmatic solution to this problem is to unregister all of the tasks associated with the program using the following routine:

function unregisterBackgroundTasks(taskName) {
        //
        // Loop through all background tasks and unregister any with the taskName
        //
        var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
        var hascur = iter.hasCurrent;
        while (hascur) {
            var cur = iter.current.value;
            if (cur.name === taskName) {
                cur.unregister(true);                
            }
            hascur = iter.moveNext();
        }
    }

This seems to work well but I do not know if there is a way to clear this “pollution” of the background task manager outside of the program except that background tasks are unregistered when a program is uninstalled.

Advertisements

Leave a Comment »

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.
Entries and comments feeds.

%d bloggers like this: