使用触发器注册后台任务
后台任务是在应用程序未运行时执行某些工作的好方法。在能够使用之前,你必须注册它们。
以下是后台任务类的示例,包括使用触发器和条件进行注册以及 Run 实现
public sealed class Agent : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// run the background task code
}
// call it when your application will start.
// it will register the task if not already done
private static IBackgroundTaskRegistration Register()
{
// get the entry point of the task. I'm reusing this as the task name in order to get an unique name
var taskEntryPoint = typeof(Agent).FullName;
var taskName = taskEntryPoint;
// if the task is already registered, there is no need to register it again
var registration = BackgroundTaskRegistration.AllTasks.Select(x => x.Value).FirstOrDefault(x => x.Name == taskName);
if(registration != null) return registration;
// register the task to run every 30 minutes if an internet connection is available
var taskBuilder = new BackgroundTaskBuilder();
taskBuilder.Name = taskName;
taskBuilder.TaskEntryPoint = taskEntryPoint;
taskBuilder.SetTrigger(new TimeTrigger(30, false));
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
return taskBuilder.Register();
}
}