UWP后台任务5次后没有运行

c2t*_*run 6 c# windows-10 uwp windows-10-universal

我正在关注https://docs.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task文档以创建一个后台任务,该任务将每15分钟运行一次并ping一项服务.

  1. 使用实现IBackgroundTask的公共密封类创建了一个Windows运行时组件项目

    namespace PeriodicBackgroundTask
    {
        public sealed class FifteenMinutePeriodicTimer : IBackgroundTask
        {
            private static readonly FileLogWriter mWriteLogToFile = new FileLogWriter();
            public FifteenMinutePeriodicTimer() { }
    
            public void Run(IBackgroundTaskInstance taskInstance)
            {
                try
                {
                    taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
                    mDeferral = taskInstance.GetDeferral();
                    mWriteLogToFile.log("Starting periodic timer at " + DateTime.Now.ToString());
    
                    // Calling method to do a Post call to a service.
    
                    mWriteLogToFile.log("Finishing periodic timer at " + DateTime.Now.ToString());
                }
                catch (Exception ex)
                {
                    mWriteLogToFile.log("Fifteen Minute periodic timer failed.", ex);
                }
                finally
                {
                    // Adding some buffer for async processes to finish.    
                    Task.Delay(TimeSpan.FromSeconds(15)).Wait();
                    mDeferral.Complete();
                }
            }
    
            private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
            {
                mWriteLogToFile.log("Fifteen minute periodic timer is canceled. {0}", reason.ToString());
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在UWP应用程序的Package.appmanifest文件中输入

    <Extension Category="windows.backgroundTasks" EntryPoint="PeriodicBackgroundTask.FifteenMinutePeriodicTimer">
      <BackgroundTasks>
        <Task Type="systemEvent" />
        <Task Type="timer" />
      </BackgroundTasks>
    </Extension>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在App.xaml.cs中的OnLaunched方法的开头注册Timer

    public async static Task RegisterBackgroundTask()
    {
        foreach (var task in BackgroundTaskRegistration.AllTasks)
        {
            if (String.Equals(task.Value.Name, TASK_NAME))
            {
                mWriteLogToFile.log("Old version of fifteen minute periodic timer found. Unregistering it.");
                BackgroundExecutionManager.RemoveAccess();
                // Unregistering so that any update in Background task can be applied.
                task.Value.Unregister(true);
                break;
            }
        }
        BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
        if (backgroundAccessStatus == BackgroundAccessStatus.DeniedByUser ||
        backgroundAccessStatus == BackgroundAccessStatus.DeniedBySystemPolicy)
        {
            mWriteLogToFile.log("Fifteen minute periodic timer registration failed, due to Request access status.");
            return;
        }
    
        BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
        builder.Name = TASK_NAME;
        builder.TaskEntryPoint = "PeriodicBackgroundTask.FifteenMinutePeriodicTimer";
        builder.SetTrigger(new TimeTrigger(15, false));
        builder.CancelOnConditionLoss = false;
    
        var backgroundTask = builder.Register();
        if (backgroundTask != null)
        {
            mWriteLogToFile.log("Fifteen minute periodic timer registration SUCCESSFUL.");
        }
        else
        {
            mWriteLogToFile.log("Fifteen minute periodic timer registration FAILED.");
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

安装应用程序后,FifteenMinuteBackgroundTimer运行5或6次.有时5,有时6.当我尝试使用Visual Studio调试任务时,我可以调试它.我不确定,为什么FifteenMinuteBackgroundTimer在5次运行后死亡.请问有谁可以告诉我如何调试此问题?

更多信息:

Windows Build:1607
Microsoft.NETCore.UniversalWindowsPlatform:5.1.0

小智 1

您很可能会遇到两项与电力相关的政策。

  1. 周期性定时器触发被认为是机会性的。根据后台使用的能源量(未通电且屏幕关闭时),您的任务可能不会被触发,以便为其他关键用户活动(例如接收短信、推送或来电)节省能源。要验证这是否是您遇到的情况:您可以在“设置->系统->电池->应用程序电池”面板中将应用程序切换为“始终允许”。
  2. 您还提到,如果屏幕关闭,当触发器运行时,网络将不起作用。在备用系统中,您需要将 IsNetworkRequested 指定为触发器注册的一部分,以便系统在任务期间将网络接口置于完全操作模式。请参阅此处的文档:https://learn.microsoft.com/en-us/uwp/api/Windows.ApplicationModel.Background.BackgroundTaskBuilder