在backgroundTask不能调用Task.Run()

编程入门 行业动态 更新时间:2024-10-26 12:21:34
本文介绍了在backgroundTask不能调用Task.Run()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I want to do something in thread at background task, so I tried using Task.Run() but it does not work.

任何人都可以告诉我另一种方式要在后台创建任务线程

Anyone can show me another way to create thread in background task.

这是我的代码:

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

当我删除等待Task.Run() for循环可以正常运行,但是当我不要删除它,循环不能运行。

When I remove await Task.Run() for loops can run normally, but when I don't remove it, for loop can not run.

推荐答案

要运行的任务或使用等待 - 异步模式在你的后台任务,你需要使用延期,否则你的任务可能会意外终止,当它到达运行结束方法。

To run tasks or use await - async pattern in your background tasks you need to use deferrals otherwise your task can terminate unexpectedly when it reaches the end of the Run method.

了解更多官方文档中的这里

Read more in the official documentation here

下面是你将如何实现在你的代码的任务延期:

Here's how you would implement task deferral in your code:

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

更多推荐

在backgroundTask不能调用Task.Run()

本文发布于:2023-11-03 07:47:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:backgroundTask   Task   Run

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!