0

我正在尝试实现 windows phone 8.1 通知后台任务。

它是用一个错误实现的!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 关键字吗?

4

1 回答 1

1

好咯咯!!!是我的错。在我的代码中,我在每次应用启动时注册了后台任务,而不检查它是否已经注册。

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

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

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

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

于 2014-08-10T05:00:31.690 回答