Check if application is running from a background

2019-06-05 07:29发布

问题:

I'm creating an UWP application with a background task. I don't want to run the background when the real application is running or suspended. Is there some way to achieve that? I’ve looked on SystemConditionType but nothing fits what I'm looking for.

回答1:

Since background tasks (except special ones) run in a separate process, there is not an elegant way to check if app is running or not since memory is not shared between the app and the background task. There are two ways that I implemented successfully:

App Service

Create an app service in the app, in the background task, try to connect to the service. If service is available, it means that the app is running. This is the favorite one when you need communication between the task and the app.

File Lock

This is the favorite one in simple scenarios that you just need to know if the app is running or not.

  1. Every time the app starts, create/open a file in local app folder, open it for write and keep it open as long as the app is running. Close it on Suspending event and re-open it on Resuming event.
  2. In the background task, attempt to open the file for writing, if attempt was successful, it means that app is not running.
  3. Close the file immediately in the background task.

Note: In the new API that is available in anniversary update, background tasks may be executed in the same process as the app. Using the new model, you won't have this problem anymore.