Search code examples
multithreadingwindows-phonewinrt-xamlbackground-task

Background Task in WP 8.1 run more than once


Im trying to implement windows phone 8.1 notification background task.

it is implemented with one bug! the toast notification message will appear in the action center more than once. sometimes 9times.

here is my code:

public sealed class my_bg_notifier: IBackgroundTask
    {
        public async void Run(IBackgroundTaskInstance taskInstance)
        {


                var deferral = taskInstance.GetDeferral();

                bool status = await notificationChecker.check();

                if (status)
                {
                    populateNotification(notificationChecker.count);
                }

                deferral.Complete();

        }

}

I tried to debug so I put a breakpoint over the line status.

and I was surprised that it is called more than once and that is why my notification will pop-up more than one time.

and the message that is showed from the debugger breakpoint clearly states that there are multiple threads doing the same job simultaneously.

[image]

so i thought to prevent running the method by more than one thread by using a boolean flag as follow:

public sealed class my_bg_notifier: IBackgroundTask
    {

        private static bool isNotBusy = true;

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            if (isNotBusy)
            {
                isNotBusy = false;
                var deferral = taskInstance.GetDeferral();

                bool status = await notificationChecker.check();

                if (status)
                {
                    populateNotification(notificationChecker.count);
                }

                deferral.Complete();
            }

            isNotBusy = true;
        }
}

but again that didn't work.

my question is :
why would a background task run more than once by multiple thread simultanously.

and How can I block this behavioud? should I use lock keyword?


Solution

  • Okkkkk!!! It was my fault. In my code i registered the background task on each app launch without checking if it is already registered.

    So i used code as below to check if my task is registered then no need to register it again.

    var taskRegistered = false;
    var exampleTaskName = "ExampleBackgroundTask";
    
    foreach (var task in Background.BackgroundTaskRegistration.AllTasks)
    {
        if (task.Value.Name == exampleTaskName)
        {
            taskRegistered = true;
            break;
         }
    }
    

    Source: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx