IBackgroundTask类中的任务类型

本文关键字:任务 类型 IBackgroundTask | 更新日期: 2023-09-27 18:17:38

我想做

async Task DoSomething()
{
   await SomeAsyncAPI();
}
async void Run()
{
   await DoSomething();
   DoAnother();
}

但是任务类型在IBackgroundTask类中不允许。我希望DoAnother()在DoSomething完成后运行

IBackgroundTask类中的任务类型

您可以使用可等待的IAsyncActionWindowsRuntimeSystemExtensions.AsAsyncAction:

public IAsyncAction DoWorkAction()
{
    return DoWorkAsync().AsAsyncAction();
}
internal async Task DoWorkAsync()
{
    await Task.Delay(100);
}
public async void Run(IBackgroundTaskInstance taskInstance)
{
   var deferral = taskInstance.GetDeferral();
   try
   {
      await DoWorkAction();
      DoAnother();
   }
   finally
   {
      deferral.Complete();
   }
}

对于Task<T>,使用IAsyncOperation<T>:

public IAsyncOperation<string> DoMoreWorkAction()
{
    return DoMoreWorkAsync().AsAsyncOperation();
}
internal async Task<string> DoMoreWorkAsync()
{
    await Task.Delay(1000);
    return "Hello";
}
public async void Run(IBackgroundTaskInstance taskInstance)
{
   var deferral = taskInstance.GetDeferral();
   try
   {
      await DoMoreWorkAction();
      DoAnother();
   }
   finally
   {
      deferral.Complete();
   }
}

要对WinRT命令样式的事件(包括IBackgroundTask.Run)使用异步方法,您需要使用延迟:

async void Run(IBackgroundTaskInstance instance)
{
  var deferral = instance.GetDeferral();
  try
  {
    await DoSomething();
    DoAnother();
  }
  finally
  {
    deferral.Complete();
  }
}