Can not call Task.Run() at backgroundTask

泄露秘密 提交于 2019-12-23 17:33:50

问题


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.

This is my code:

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

    }
}

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


回答1:


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

}


来源:https://stackoverflow.com/questions/38066145/can-not-call-task-run-at-backgroundtask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!