我想做
async Task DoSomething()
{
await SomeAsyncAPI();
}
async void Run()
{
await DoSomething();
DoAnother();
}
但IBackgroundTask类中不允许使用任务类型。我想在DoSomething完成后运行DoAnother()。
答案 0 :(得分:4)
您可以使用等待的IAsyncAction
和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();
}
}
对于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();
}
}
答案 1 :(得分:2)
要将异步方法与WinRT命令样式事件(包括IBackgroundTask.Run
)一起使用,您需要使用deferrals:
async void Run(IBackgroundTaskInstance instance)
{
var deferral = instance.GetDeferral();
try
{
await DoSomething();
DoAnother();
}
finally
{
deferral.Complete();
}
}