BackgroundTask没有触发

时间:2016-01-04 19:11:41

标签: c# uwp

我的后台任务注册但从未触发。我试图删除整个项目以删除所有任务,更改TaskBuilder类上的名称,并使用不同的条件。但似乎没有任何效果。我有时会收到错误消息,说明它无法向我显示错误。

我在这里构建它:

public async void RegisterBackgroundTask()
{
    var taskRegistered = false;
    var TaskName = "TimeTriggeredTask";

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

    var tommorowMidnight = DateTime.Today.AddDays(1);
    var timeTilMidnight = tommorowMidnight - DateTime.Now;
    var minutesTilMidnight = (uint)timeTilMidnight.TotalMinutes;
    if (!taskRegistered)
    {
        var task = RegisterBackgroundTask("TaskBuilderClass",
                                          "TimeTriggeredTask",
                                           new TimeTrigger(minutesTilMidnight, false),
                                           new SystemCondition(SystemConditionType.InternetAvailable));
        await task;
        CheckPremieres();
    }
}

构建器方法:

public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition)
{

    await BackgroundExecutionManager.RequestAccessAsync();

    var builder = new BackgroundTaskBuilder();

    builder.Name = name;
    builder.TaskEntryPoint = taskEntryPoint;
    builder.SetTrigger(trigger);
    builder.AddCondition(condition);
    BackgroundTaskRegistration task = builder.Register();

    //
    // Remove previous completion status from local settings.
    //
    var settings = ApplicationData.Current.LocalSettings;
    settings.Values.Remove(name);

    return task;
}

这是我也添加到清单中的任务构建器类:

public sealed class TaskBuilderClass : IBackgroundTask
{
    //
    // The Run method is the entry point of a background task.
    //
    public void Run(IBackgroundTaskInstance taskInstance)
    {            
        //
        // Query BackgroundWorkCost
        // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
        // of work in the background task and return immediately.
        //
        var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
        var settings = ApplicationData.Current.LocalSettings;
        settings.Values["BackgroundWorkCost"] = cost.ToString();

        App.nHandler.CheckPremieres();
    }   
}

1 个答案:

答案 0 :(得分:0)

我非常确定任务需要在自己的Windows运行时组件中;我一直这样做。 Microsoft sample on GitHub还在单独的项目中执行任务。

尝试这样做。并且不要忘记从您的应用程序中引用新创建的项目。这是我最常忘记的事情。

一旦你这样做,我还建议你先从Visual Studio Debug Location toolbar触发任务,以确保所有内容都配置正确。它应该出现在下拉列表中,并且应该从此处正常工作,否则它在计划时也不会起作用。