thanhbebi
thanhbebi

Reputation: 163

Task type in a IBackgroundTask class

I want to do

async Task DoSomething()
{
   await SomeAsyncAPI();
}

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

but Task type is not allowed in IBackgroundTask class. I want DoAnother() run after DoSomething completed.

Upvotes: 2

Views: 1375

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You can use the awaitable IAsyncAction and WindowsRuntimeSystemExtensions.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();
   }
}

For Task<T>, use 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();
   }
}

Upvotes: 5

Stephen Cleary
Stephen Cleary

Reputation: 456577

To use asynchronous methods with WinRT command-style events (including IBackgroundTask.Run), you need to use deferrals:

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

Upvotes: 3

Related Questions