检查应用程序是否正在从后台任务运行 [英] Check if application is running from a background task

查看:39
本文介绍了检查应用程序是否正在从后台任务运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个带有后台任务的 UWP 应用程序.我不想在真正的应用程序运行或挂起时运行后台.有什么方法可以实现吗?我看过 SystemConditionType 但没有什么适合我正在寻找的.

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.

推荐答案

由于后台任务(特殊任务除外)在单独的进程中运行,由于内存未共享,因此没有一种优雅的方法来检查应用程序是否正在运行在应用程序和后台任务之间.我成功实施的方法有两种:

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:

应用服务

在应用中创建应用服务,在后台任务中,尝试连接该服务.如果服务可用,则表示该应用程序正在运行.当您需要在任务和应用之间进行通信时,这是最喜欢的一种.

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.

文件锁定

这是在您只需要知道应用程序是否正在运行的简单场景中最喜欢的一个.

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

  1. 每次应用程序启动时,在本地应用程序文件夹中创建/打开一个文件,打开它进行写入并在应用程序运行期间保持打开状态.在 Suspending 事件中关闭它,并在 Resuming 事件中重新打开它.
  2. 在后台任务中,尝试打开文件进行写入,如果尝试成功,则表示该应用程序未运行.
  3. 在后台任务中立即关闭文件.

注意:在周年更新中可用的新 API 中,后台任务可能会在 与应用程序相同的流程.使用新模型,您将不再遇到此问题.

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.

这篇关于检查应用程序是否正在从后台任务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆