I unregister my task (I removed the If to make sure all tasks are removed.):
foreach (var taskA in BackgroundTaskRegistration.AllTasks)
{
//if (taskA.Value.Name == exampleTaskName)
{
taskA.Value.Unregister(true);
}
}
Then I try to recreate it, and check if it doesn't exist:
private async void LaunchBackground()
{
await BackgroundExecutionManager.RequestAccessAsync();
foreach (var taskA in BackgroundTaskRegistration.AllTasks)
{
if (taskA.Value.Name == exampleTaskName)
{
await new ApplicationTrigger().RequestAsync();
return;
}
}
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "Background.BackgroundTask";
ApplicationTrigger _AppTrigger = new ApplicationTrigger();
builder.SetTrigger(_AppTrigger);
builder.Register();
await _AppTrigger.RequestAsync();
}
My task now only a defferal and does some other stuff, releasing it when cancellled:
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
AddWatched();
}
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_deferral.Complete();
}
But when I try to cancel and unregister the task, it just goes suspended. When I launch it again, it behaves weridly (I think there are two instances of it now, which both try to do the same thing at the same time).
I would ideally like to be able to kill the background task instead of backgronuding it - or if that doesn't work, if the task is suspended it should be unsuspended instead of another one created AND the old one being unsuspended.
When you want to cancel, set a Boolean property in ApplicationSettings from your app. In your background task, periodically check this property during execution and if set, cancel the process.