Why is my background task running twice on trigger?

Viewed 57

I am having trouble fixing an issue with my background task running twice.

I am using debug.WriteLine("1") inside the Run() to observe how many times the code is being run as seen in this link:

public async void Run(IBackgroundTaskInstance taskInstance)
{
    // Get a deferral so that the service isn't terminated.
    _deferral = taskInstance.GetDeferral();
    Debug.WriteLine("1");
    _deferral.Complete();
}

Each time my internet becomes available it prints 1 twice. this should only happen once. How do I get it to run the WriteLine just one time?

EDIT: I am certain its something to do with the trigger, as when I am not connected to the internet and then connect, it triggers once, whereas if I'm already connected and then disconnect and reconnect it prints twice.

The below code is run in the main UWP app to register the task:

public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint, string taskName, IBackgroundTrigger trigger, IBackgroundCondition condition)
{
    // Check for existing registrations of this background task.
    foreach (var cur in BackgroundTaskRegistration.AllTasks) {
        if (cur.Value.Name == taskName) {
            // The task is already registered.
            return (BackgroundTaskRegistration)(cur.Value);
        }
    }

    // Register the background task.
    var builder = new BackgroundTaskBuilder();
    builder.Name = taskName;
    builder.TaskEntryPoint = taskEntryPoint;
    builder.SetTrigger(trigger);

    if (condition != null) {
        builder.AddCondition(condition);
    }

    BackgroundTaskRegistration task = builder.Register();
    return task;
}

public MainPage()
{
    this.InitializeComponent();

    RegisterBackgroundTask("AppService.UpdateTask", "ServiceM", new SystemTrigger(SystemTriggerType.InternetAvailable, false), new SystemCondition(SystemConditionType.InternetAvailable));
} 
0 Answers
Related