简体   繁体   English

后台任务自发完成C#

[英]Background task spontaneous completion C#

Register a background task:注册一个后台任务:

    string myTaskName = "Task";

   foreach (var cur in BackgroundTaskRegistration.AllTasks)
        if (cur.Value.Name == myTaskName)
        {
           return;
        }

   await BackgroundExecutionManager.RequestAccessAsync();

   BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder 
   { 
        Name = "Task", 
        TaskEntryPoint = "Background.Task"
   };
   taskBuilder.SetTrigger(new TimeTrigger(15, true));
   BackgroundTaskRegistration myFirstTask = taskBuilder.Register();

Background task is created in the Windows Runtime Component as a separate class:后台任务在 Windows 运行时组件中创建为一个单独的类:

public sealed class Task : IBackgroundTask 
        {
            public async void Run(IBackgroundTaskInstance taskInstance)
            {
                BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

//logic, send http get request, connect to db

                deferral.Complete();
            }
}

When it is time to perform task- it may run random number of times (1 - 15 times) and then spontaneously terminated and no longer starts,to solve this problem need to re-register task.到了执行任务的时候——它可能会运行随机次数(1-15次)然后自发终止不再启动,要解决这个问题需要重新注册任务。 What could be the reason?可能是什么原因?

VS show this error when i want run task:当我想要运行任务时,VS 显示此错误:在此处输入图片说明

On Windows Phone periodic background tasks are executed at an interval of a minimum of 30 minutes.在 Windows Phone 上,周期性后台任务以至少 30 分钟的间隔执行。

Windows has a built-in timer that runs background tasks in 15-minute intervals. Windows 有一个内置计时器,每隔 15 分钟运行一次后台任务。 Note that on Windows Phone, the interval is 30 minutes.请注意,在 Windows Phone 上,间隔为 30 分钟。

(Source: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977059.aspx?f=255&MSPPError=-2147217396 ) (来源: https : //msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977059.aspx?f=255&MSPPError=-2147217396

If I were you I'd change the time interval to something more safe (such as 60 minutes) - you can always try smaller intervals later.如果我是你,我会将时间间隔更改为更安全的时间(例如 60 分钟)——您以后可以尝试更小的时间间隔。 And take a look at the oneShot flag, which is set to true in your case.并查看oneShot标志,在您的情况下该标志设置为true Set it to false to make your task run more than once.将其设置为false以使您的任务运行多次。

Also your exception does not look healthy.此外,您的异常看起来也不健康。 You said it even occurs with the background task being empty - you should fix that, just to be safe.你说它甚至在后台任务为空时发生 - 你应该解决这个问题,只是为了安全。

I'd suggest you to manually start and debug your backgorund task a couple of times using the lifecycle feature in Visual Studio.我建议您使用 Visual Studio 中的生命周期功能手动启动和调试 backgorund 任务几次。 Maybe there are other things that cause your task to die.也许还有其他事情会导致您的任务终止。

But first check the interval.但首先检查间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM