使用觸發器註冊後臺任務
後臺任務是在應用程式未執行時執行某些工作的好方法。在能夠使用之前,你必須註冊它們。
以下是後臺任務類的示例,包括使用觸發器和條件進行註冊以及 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();
}
}