Multithreading WP 8.1中的后台任务多次运行

Multithreading WP 8.1中的后台任务多次运行,multithreading,windows-phone,winrt-xaml,background-task,Multithreading,Windows Phone,Winrt Xaml,Background Task,我正在尝试执行windows phone 8.1通知后台任务 它是用一个bug实现的! toast通知消息将多次出现在操作中心中。有时9次 这是我的密码: public sealed class my_bg_notifier: IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = tas

我正在尝试执行windows phone 8.1通知后台任务

它是用一个bug实现的! toast通知消息将多次出现在操作中心中。有时9次

这是我的密码:

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();

        }

}
我试图调试,所以在行状态上设置了一个断点

我很惊讶它被多次调用,这就是为什么我的通知会弹出不止一次

调试器断点显示的消息清楚地表明有多个线程同时执行相同的任务

因此,我想通过使用布尔标志防止多个线程运行该方法,如下所示:

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;
        }
}
但这同样没有起作用

我的问题是:
为什么后台任务会由多个线程同时运行多次


我怎样才能阻止这种行为?我应该使用lock关键字吗?

OKKKK!!!是我的错。在我的代码中,我在每次应用程序启动时都注册了后台任务,但没有检查它是否已经注册

因此,我使用下面的代码检查我的任务是否已注册,然后无需再次注册

var taskRegistered = false;
var exampleTaskName = "ExampleBackgroundTask";

foreach (var task in Background.BackgroundTaskRegistration.AllTasks)
{
    if (task.Value.Name == exampleTaskName)
    {
        taskRegistered = true;
        break;
     }
}
资料来源: