gpt4 book ai didi

c# - 无法在 backgroundTask 调用 Task.Run()

转载 作者:行者123 更新时间:2023-11-30 14:49:56 24 4
gpt4 key购买 nike

我想在后台任务的线程中做一些事情,所以我尝试使用 Task.Run() 但它不起作用。

任何人都可以告诉我另一种在后台任务中创建线程的方法。

这是我的代码:

   public sealed class KatzBackgroundTask : IBackgroundTask
{

public void Run(IBackgroundTaskInstance taskInstance)
{
RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
string content = notification.Content;
System.Diagnostics.Debug.WriteLine(content);
testLoop();
}

async void testLoop()
{
await Task.Run(() =>
{
int myCounter = 0;
for (int i = 0; i < 100; i++)
{
myCounter++;
//String str = String.Format(": {0}", myCounter);
Debug.WriteLine("testLoop runtimeComponent : " + myCounter);
}
}
);

}
}

当我移除await Task.Run()时for循环可以正常运行,但是当我不移除它时,for循环无法运行。

最佳答案

要运行任务或在后台任务中使用 await - async 模式,您需要使用延迟,否则您的任务可能会在到达 Run 方法末尾时意外终止。

在官方文档中阅读更多信息 here

以下是如何在代码中实现任务延迟:

public sealed class KatzBackgroundTask : IBackgroundTask
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
public async void Run(IBackgroundTaskInstance taskInstance)
{
RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
string content = notification.Content;
System.Diagnostics.Debug.WriteLine(content);
await testLoop();
_deferral.Complete();
}

async Task testLoop()
{
await Task.Run(() =>
{
int myCounter = 0;
for (int i = 0; i < 100; i++)
{
myCounter++;
//String str = String.Format(": {0}", myCounter);
Debug.WriteLine("testLoop runtimeComponent : " + myCounter);
}
}
)

}

关于c# - 无法在 backgroundTask 调用 Task.Run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38066145/

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