无法在backgroundTask上调用Task.Run()

时间:2016-06-28 02:32:59

标签: c# uwp windows-10-mobile background-task

我想在后台任务的线程中做一些事情,所以我尝试使用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循环无法运行。

1 个答案:

答案 0 :(得分:5)

要在后台任务中运行任务或使用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);
           }
       }
   )

}