简体   繁体   English

一次注册后台任务

[英]Register Background Task Once

I have a background task that registers when the user enters the app using this code: 我有一个后台任务,当用户使用以下代码进入应用程序时会注册该任务:

            await BackgroundExecutionManager.RequestAccessAsync();

            BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "First Task", TaskEntryPoint = "myTask.FirstTask" };
            taskBuilder.SetTrigger(new TimeTrigger(15, false));
            BackgroundTaskRegistration myFirstTask = taskBuilder.Register();

It works fine, and the task registers, however it continues to register again every time the app opens. 它可以正常运行,并且可以注册任务,但是每次打开应用程序后,它都会继续重新注册。 Is there any way, using if , for example, to detect if a task is registered, therefore only registering a task once and not repeating the same process over and over again? 有没有什么办法,使用if ,例如,如果一个任务是记录的检测,因此只能注册一次任务,而不是一遍又一遍地重复同样的过程?

This problem was discovered by clicking on 'lifecycle events', which revealed about 15 instances of 'First Task', if that helps. 通过单击“生命周期事件”发现了此问题,如果有帮助,它将揭示大约15个“第一任务”实例。

Use the BackgroundTaskRegistration.AllTasks collection to check whether your task has already been registered: 使用BackgroundTaskRegistration.AllTasks集合检查您的任务是否已经注册:

if (BackgroundTaskRegistration.AllTasks.Values.Any(b => b.Name == "First Task"))
{
    // Already registered
}

You can use a isolated storage setting for this. 您可以为此使用隔离的存储设置。 When the app starts look for an isolated storage setting if the setting is not there register the background task and create the setting. 当应用程序启动时,查找一个孤立的存储设置(如果该设置不存在),注册后台任务并创建设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM