简体   繁体   English

当你无法等待时,你怎么能等待任务

[英]How can you await a Task when you can't await

I'm developing a Windows 8 Runtime Component so the public interface can't contain Task<T> as it's not a windows runtime type. 我正在开发一个Windows 8运行时组件,因此公共接口不能包含Task<T>因为它不是Windows运行时类型。

This means I can't mark the method as async and can't await the private async methods in my library. 这意味着我无法将该方法标记为async ,也无法await我的库中的private async方法。 This is leading to some confusion about how to handle my application logic. 这导致了一些关于如何处理我的应用程序逻辑的混淆。

This is how I'd do what I want synchronously. 这就是我如何做我想要的同步。

Result r = TryGetAuthResultFromFile();
if(r != null)
{
    return r;
}

r = GetAuthResultFromWebAuthenticationBroker();
return r;

The problem is that TryGetResultFrom file are async Task<Result> methods and the method that's returning r is returning IAsyncOperation<Result> 问题是TryGetResultFrom文件是async Task<Result>方法,并且返回r的方法返回IAsyncOperation<Result>

I've tried this (this isn't complete code but the theory can be seen, handle the results in continuations and return them, I'd have to do some frigging of results to IAsyncOperation types). 我已经尝试过这个(这不是完整的代码,但可以看到理论,在延续中处理结果并返回它们,我必须对IAsyncOperation类型进行一些结果处理)。

TryGetAuthResultFromFile().ContinueWith(x=>
{
    if(x.Result != null)
    {
        return x.result;
    }

    GetAuthResultFromWebAuthenticationBroker().ContinueWith(y=>
    {
        return y.Result;
    });
});

The problem with this is that the WebAuthenticationBroker doesn't seem work if it's not being called from the UI thread. 这样做的问题是,如果没有从UI线程调用WebAuthenticationBroker它似乎不起作用。 It throws a helpful NotImplementedException without a useful error message. 它抛出一个有用的NotImplementedException而没有有用的错误消息。

How can I call TryGetAuthResultFromFile then wait for the result, then call GetAuthResultFromWebAuthenticationBroker ? 如何调用TryGetAuthResultFromFile然后等待结果,然后调用GetAuthResultFromWebAuthenticationBroker

Your interface can't use Task / Task<T> , but it can use IAsyncAction / IAsyncOperation<T> . 您的界面不能使用Task / Task<T> ,但它可以使用IAsyncAction / IAsyncOperation<T>

Your implementation can use Task / Task<T> if you have a wrapper that calls AsAsyncAction / AsAsyncOperation / AsyncInfo.Run as appropriate. 如果您有一个适当调用AsAsyncAction / AsAsyncOperation / AsyncInfo.Run的包装器,您的实现可以使用Task / Task<T>

public interface IMyInterface
{
  IAsyncOperation<MyResult> MyMethod();
}

public sealed class MyClass: IMyInterface
{
  private async Task<MyResult> MyMethodAsync()
  {
    var r = await TryGetAuthResultFromFileAsync();
    if (r != null)
      return r;
    return await GetAuthResultFromAuthenticationBrokerAsync();
  }

  public IAsyncOperation<MyResult> MyMethod()
  {
    return MyMethodAsync().AsAsyncOperation();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM