我想做的事情在后台任务线程的东西,所以我尝试使用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()
发布评论