gpt4 book ai didi

c# - UWP:为什么我的后台任务(使用 TimeTrigger)会超出 CPU 配额?

转载 作者:太空宇宙 更新时间:2023-11-03 23:10:57 26 4
gpt4 key购买 nike

在我的 UWP 应用程序中,我有一个由 TimeTrigger 触发的后台任务。在后台任务的代码中,我有这个片段(我的示例中的“第一个事件”和“第二个事件”几乎不消耗任何资源):

var deferral = args.TaskInstance.GetDeferral();
await Task.Run(async () =>
{
//... first activity

await Task.Delay(TimeSpan.FromSeconds(90.0));

//... second activity, 90 seconds later

});

所以我的问题是:

  1. 为什么上面的代码可以工作,正如文档中明确指出的那样“后台任务被限制为 30 秒的挂钟使用”?

  2. 每个 TriggerType 的 CPU 配额记录在哪里?

最佳答案

1.Why does the above code work, as the documentation clearly says "Background tasks are limited to 30 seconds of wall-clock usage"?

正如Background task resource constraints中所说:

Background tasks are limited to 30 seconds of wall-clock usage.

此约束也适用于 TimeTrigger。但是您的代码有效,我想这是因为您正在使用 Visual Studio 调试后台任务。附加 Visual Studio 调试器后,Visual Studio 将控制后台任务。后台任务用于帮助开发人员进行调试。如果没有调试器,超过 CPU 配额的后台任务应该被操作系统取消。

例如,如果我们使用如下后台任务:

public sealed class MyBackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Test.txt", CreationCollisionOption.OpenIfExists);
await FileIO.AppendTextAsync(file, $"{DateTime.Now.ToString()} first activity{Environment.NewLine}");

await Task.Delay(TimeSpan.FromSeconds(90.0));

await FileIO.AppendTextAsync(file, $"{DateTime.Now.ToString()} second activity{Environment.NewLine}");

deferral.Complete();
}
}

然后通过旁加载此应用程序包来测试它。 (有关如何旁加载 UWP 应用程序,请参阅 Packaging UWP apps)。一旦后台任务被触发,我们可以在Test.txt文件中找到(这个文件通常在%USERPROFILE%\AppData\Local\Packages\{Package family name}\LocalState), 输出如下:

9/2/2016 3:06:35 PM first activity
9/2/2016 3:20:15 PM first activity

只有“第一事件”没有“第二事件”。而在事件 View 中,我们可以获得如下信息:
enter image description here这些信息位于应用程序和服务日志 → Microsoft → Windows → BackgroundTaskInfrastructure → 操作下。

2.Where is the CPU quota documented per TriggerType?

没有关于每种触发器类型的 CPU 配额的文档。引用 Background task guidance :

CPU quotas: Background tasks are limited by the amount of wall-clock usage time they get based on trigger type. Most triggers are limited to 30 seconds of wall-clock usage, while some have the ability to run up to 10 minutes in order to complete intensive tasks.

只有 ApplicationTriggerMaintenanceTriggerDeviceUseTrigger 等少数触发器的使用时间超过 30 秒。后台任务应该是轻量级的,以节省电池生命周期并为前台应用程序提供更好的用户体验。最好只在后台运行轻量级代码并使其在 30 秒内完成。

关于c# - UWP:为什么我的后台任务(使用 TimeTrigger)会超出 CPU 配额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com