user3927312
user3927312

Reputation: 824

Stopping a background Task

How can I stop an already running background task without the user going to the UI of my application?

Upvotes: 0

Views: 136

Answers (1)

Romasz
Romasz

Reputation: 29792

If your BackgroundTask is synchronous, then you need just to leave the Run method to finish with the task.

If you have asynchronous BackgroundTask, you need to use BackgroundTaskDeferral - obtain at the beginning and call Complete() once you finish your work. As it's said at MSDN:

  1. If you run any asynchronous code in your background task, then your background task needs to use a deferral. If you don't use a deferral, then the background task process can terminate unexpectedly if the Run method completes before your asynchronous method call has completed.

You should be also aware that the OS can terminate your task earlier - if the task exceeded the limits or trigger condition is no longer fulfilled - for example MaintenanceTrigger.

When you finish with asynchronous BackgroundTask, pay attention to finish/cancel all Tasks, you may need to implement CancellationToken.

Upvotes: 1

Related Questions