From a UWP app I start the following UWP background task using BackgroundTaskBuilder
:
namespace Background.UWP
{
public sealed class BackgroundTask : IBackgroundTask
{
private WatchLoop _watchLoop;
public void Run(IBackgroundTaskInstance taskInstance)
{
ApplicationTriggerDetails details = taskInstance.TriggerDetails as ApplicationTriggerDetails;
var arg = details.Arguments["MyArg"].ToString();
// Start an infinite loop that periodically does some checks
_watchLoop = new WatchLoop(arg, new ToastNotification());
_watchLoop.Start();
}
}
}
First question: Does this background task run indefinitely if not cancelled by certain check conditions?
Second question: In my UWP app, how can I check if this background task is already running? I want to avoid starting a second background task. Is there a global handle of this task that I can store (serialized) in global storage (e.g. database) and use in the next instance of the UWP app?
I solved this problem as follows:
Before registering and starting my background task I do a check like in Junjie Zhu's example. I register and start the background task only if it is not yet registered.
I then put a try ... finally
around my _watchLoop.Start()
loop and in the finally block I put some code to unregister the background task.
This should work in normal operation. However, if I stop all processes in VS Debugger, the background task stops immediately without reaching the finally
block. For this purpose I declare a compile switch that during development always unregisters my background task before starting.