Background task spontaneous completion C#

222 views Asked by At

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:

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. What could be the reason?

VS show this error when i want run task:enter image description here

1

There are 1 answers

2
Fred On BEST ANSWER

On Windows Phone periodic background tasks are executed at an interval of a minimum of 30 minutes.

Windows has a built-in timer that runs background tasks in 15-minute intervals. Note that on Windows Phone, the interval is 30 minutes.

(Source: 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. And take a look at the oneShot flag, which is set to true in your case. Set it to false to make your task run more than once.

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. Maybe there are other things that cause your task to die.

But first check the interval.