UWP计时器后台任务无法运行

时间:2017-03-16 15:29:02

标签: c# uwp win-universal-app

使用以下参考资料,我尝试在UWP应用程序中进行后台任务:

https://docs.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task

https://docs.microsoft.com/en-us/windows/uwp/launch-resume/run-a-background-task-on-a-timer-

https://www.youtube.com/watch?v=H18HrUin46I

强制后台任务在调试模式下运行时,YouTube视频中显示的一切正常,但应用程序上的调试/发布版本不会启动它自己的15分钟后台任务。这是代码:

MainPage.xaml.cs中

using TimerBG;

bool taskRegistered = false;

foreach (var task in BackgroundTaskRegistration.AllTasks)
{
    if (task.Value.Name == nameof(BG))
    {
        task.Value.Unregister(true);
    }
}
if(!taskRegistered)
{
    Setup();
}

public async static void Setup()
{
    BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();

    var builder = new BackgroundTaskBuilder();
    builder.Name = nameof(BG);
    builder.TaskEntryPoint = typeof(BG).ToString();
    TimeTrigger trig = new TimeTrigger(15, false);
    builder.SetTrigger(trig);
    SystemCondition userCondition = new SystemCondition(SystemConditionType.UserNotPresent);
    builder.AddCondition(userCondition);
    builder.CancelOnConditionLoss = false;
    builder.Register();
}

BG.cs

using Windows.ApplicationModel.Background;
using Windows.Storage;

namespace TimerBG
{
    public sealed class BG : IBackgroundTask
    {
        BackgroundTaskDeferral _deferral;

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
            await FileIO.WriteTextAsync(sampleFile, DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString());

            _deferral.Complete();
        }
    }
}

包清单后台任务属性设置为“Timer”,入口点为“TimerBG.BG”。

1 个答案:

答案 0 :(得分:1)

阅读文章后找到解决方案:

https://docs.microsoft.com/en-us/windows/uwp/launch-resume/debug-a-background-task

后台任务和Visual Studio程序包部署

如果使用Visual Studio部署使用后台任务的应用程序,然后更新Manifest Designer中指定的版本(主要和/或次要),则随后使用Visual Studio重新部署应用程序可能会导致应用程序的后台任务失速。这可以解决如下:

  • 如果您已使用Visual Studio部署应用程序并且其后台任务现已停止,请重新启动或注销/登录以使应用程序的后台任务再次运行。