问题
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