我想在后台任务的线程中做一些事情,所以我尝试使用 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循环无法运行。
要运行任务或在后台任务中使用等待 - 异步模式,您需要使用延迟,否则您的任务在到达任务末尾时可能会意外终止。Run
方法。
阅读官方文档了解更多内容here https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task
以下是在代码中实现任务延迟的方法:
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);
}
}
)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)