如果应用程序正在启动,如何停止后台任务? [英] How to stop the background task if the app is starting?

查看:48
本文介绍了如果应用程序正在启动,如何停止后台任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,应用和后台任务都访问一个文件,无论哪个先打开文件,另一个都会失败.

In my app both the app and a background task access a file and whichever opens the file first, the other one will fail.

为了避免这种情况发生,我想在用户打开应用程序时停止后台任务,如果应用程序已经打开,则不要运行后台.

to avoid that happening, I want to stop the background task when the user opens the app, and don't run the background if the app is already open.

如何从后台任务知道应用程序是否正在运行?以及如何在应用程序启动之前停止它?谢谢.

How to know from background task if app is running or not? and how to stop it before app starts? thanks.

这是我注册后台任务的方式:

This is how I register the background task:

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();

有一个 UserNotPresent条件只有在用户不存在时才能运行.但我现在不明白这意味着用户正在使用应用程序或手机.

There is a UserNotPresent condition that specifies the task can run only if user is not present. But I don't understand by present it means user is working with the app, or with phone.

推荐答案

UserNotPresent 条件表示用户当前并未使用整个设备.

The UserNotPresent condition indicates that the user isn't currently using the entire device.

您的任务是进程内后台任务还是进程外后台任务?我建议使用进程内任务来避免困难的跨进程通信场景并简化项目结构.

Is your task an in-process background task or an out-of-process background task? I would suggest using in-proc tasks to avoid difficult cross-proc communication scenarios and to simplify the structure of your projects.

回到确定应用程序是否从后台任务启动的实际问题:

对于进程中的任务,您可以检查应用程序的可见性状态以查看它是否在前台.这可以通过几种不同的方式完成:

For in-process tasks you can check the visibility state of the app to see if it is in the foreground. This can be done in a couple different ways:

  • 在 LeavingBackground 中将 IsInForeground 标志设置为 true,然后在 EnteredBackground 中将其设置为 false.然后,您可以检查标志以查看应用是否在前台运行.
  • 使用窗口的可见性.使用 CoreWindow.GetForCurrentThread().Visible 或 Window.Current.Visible 将使您能够查看应用程序是否在前台、最小化或在后台无头运行.两者在前台时为真,在最小化时为假.CoreWindow.GetForCurrentThread() 将返回 null 并尝试访问 Window.Current 将在应用程序无头时抛出异常.

对于进程外任务,您可以与前台应用通信以确定它是否存在.这可以使用此处建议的方法之一来完成:检查应用程序是否从后台任务运行

For out-of-process tasks you can communicate with the foreground app to determine whether it is present. This can be accomplished using one of the methods suggested here: Check if application is running from a background task

如何停止后台任务

确保从后台任务实例的延迟被释放,然后从您的主要方法返回(对于进程外的 Run() 或进程内的 BackgroundActivated()).如果进程中没有其他东西在运行,那么它将退出.

Ensure the deferral from the background task instance is released and then just return from your primary method (either Run() for out-of-proc or BackgroundActivated() for in-proc). If there is nothing else running in the process then it will exit.

这篇关于如果应用程序正在启动,如何停止后台任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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