我可以为UWP的BackgroundTask设置多个触发器吗?

时间:2016-12-06 13:05:16

标签: c# .net uwp windows-10 background-task

我无法在MSDN文档中找到我是否只能将一个触发器(使用SetTrigger()方法)设置为后台任务或多个。如果我想在计时器上以及以编程方式触发任务,那么我需要TimerTrigger和ApplicationTrigger?还可以使用AddCondition()?

设置多个条件

1 个答案:

答案 0 :(得分:3)

后台任务注册只能有一个触发器,但是您可以为同一个后台任务进行多次注册。

您可以拥有任意数量的条件。

例如,此处,MyBackgroundTask在互联网连接可用时由TimeTriggerUserPresent触发器触发。在这两种情况下都会调用MyBackgroundTask.Run()

public sealed class MyBackgroundTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        // your task code here
    }

    public void Register()
    {
         RegisterWithTrigger(BackgroundTaskSuffixTime,          new TimeTrigger((uint) RefreshInterval.TotalMinutes, false));
         RegisterWithTrigger(BackgroundTaskSuffixUserPresent,   new SystemTrigger(SystemTriggerType.UserPresent, false));
    }

    private static IBackgroundTaskRegistration RegisterWithTrigger(string taskSuffix, IBackgroundTrigger trigger)
    {
        var taskEntryPoint  = typeof(MyBackgroundTask).FullName;
        var taskName        = taskEntryPoint + taskSuffix;

        var registration            = BackgroundTaskRegistration.AllTasks.Select(x => x.Value).FirstOrDefault(x => x.Name == taskName);
        if(registration != null) return registration;

        var taskBuilder             = new BackgroundTaskBuilder();
        taskBuilder.Name            = taskName;
        taskBuilder.TaskEntryPoint  = taskEntryPoint;
        taskBuilder.SetTrigger(trigger);
        taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
        return taskBuilder.Register();
    }
}

不要忘记在应用程序清单中声明所有适当的触发器:

<Extension Category="windows.backgroundTasks" EntryPoint="Background.MyBackgroundTask">
  <BackgroundTasks>
    <Task Type="systemEvent" />
    <Task Type="timer" />
  </BackgroundTasks>
</Extension>