How to stop the background task if the application starts?

In my application, the application and the background job access the file, and depending on what opens the file first, the other will fail.

To avoid this, I want to stop the background task when the user opens the application, and do not start the background if the application is already open.

How to find out from the background task if the application is running or not? and how to stop it before launching applications? thanks.


This is how I register the background job:

var result = await BackgroundExecutionManager.RequestAccessAsync(); var builder = new BackgroundTaskBuilder(); builder.Name = taskName; builder.TaskEntryPoint = taskEntryPoint; builder.SetTrigger(trigger); builder.AddCondition(condition); BackgroundTaskRegistration task = builder.Register(); 

There is a UserNotPresent condition that indicates that a task can only be completed if the user is absent. But I still do not understand what this means that the user is working with the application or with the phone.

+1
c # windows-10 uwp
source share
1 answer

The UserNotPresent clause indicates that the user is not currently using the entire device.

Is your task a background task in the process or a background task outside the process? I would suggest using in-process tasks to avoid complex scenarios of exchange between passes and simplify the structure of your projects.

Let's get back to your actual question of determining whether an application is associated with a background task:

In the tasks of the process, you can check the visibility state of the application to see if it is in the foreground. There are several ways to do this:

  • Set the IsInForeground flag to true in the LeavingBackground, which is then set to false in the EnteredBackground. You can then check the flag to see if the application is in the foreground.
  • Use window visibility. Using CoreWindow.GetForCurrentThread (). Visible or Window.Current.Visible will let you know if the application is in the foreground, minimized or running headless in the background. Both values ​​are true when foreground and false when minimized. CoreWindow.GetForCurrentThread () will return null and try to access Window.Current will throw an exception while the application is headless.

For tasks outside the process, you can contact the foreground application to determine if it is present. This can be done using one of the methods suggested here: Check if the application is running from a background task

How to stop a background task

Ensure that deferment is released from the background task instance, and then simply return from the main method (either Run () for non-proc or BackgroundActivated () for in-proc). If nothing works in this process, it exits.

0
source share

All Articles