Search code examples
c#uwpbackground-processbackground-taskout-of-process

UWP in-process background task when app is closed


Does the in-process background task, defined via the OnBackgroundActivated method, run even if the main application is closed or suspended or must I implement an out-of-process background task?

The documentation is not clear on this.

I've written out-of-process background tasks before and they run even when the app is not. However, it seems to me that an in-process background task won't run unless the app is active. I've used a deferral, as suggested in the documentation, to avoid the task being closed, and I've set the oneShot to false when registering the task. The task takes no longer than 10 seconds. The task is registered and can be run manually from Visual Studio, but doesn't seem to run automatically, if the app is closed.

protected async override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
    base.OnBackgroundActivated(args);
    IBackgroundTaskInstance taskInstance = args.TaskInstance;
    BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
    await RunBackgroundWork();
    deferral.Complete();
}

In summary, if you need to create a background task that should run even if the main app is not open, can this be done with an in-process background task, or must an out-of-process background task be used?


Solution

  • Turns out, contrary to the answer the condescending Microsoft employee provided, that the background task will run if the app is closed, even if it is implemented as an in-process background task.

    If the background task is implemented as an in-process task, then the OnBackgroundActivated method will be used as the entry point, in case the app is not running. Otherwise, the method will be called while the app is running.

    The reason why there were problems with the background task starting was that I used a condition (namely the SystemConditionType.UserPresent) on the task. This behaves very unpredictably. However, I tested (by waiting for several calls) both the in-process and out-of-process approach and the task gets run in both cases, even if the app is closed.

    If a task deferral is used, the background task should not be terminated even if the user closes the app.

    In conclusion, at the time of writing this post (October 17th, 2020) the documentation does not clearly explain this behavior and the aforementioned condescending misinterpretation by, ironically enough, Microsoft's own employee only proves that point.