在 Singleton.Instance 后面调用异步方法

Calling async method behind Singleton.Instance

我有一个基本的单例 class,但是单例有一个像这样的异步方法:

public sealed class AddInHandler
{
    private static readonly AddInHandler instance = new AddInHandler();

    static AddInHandler()
    {
    }

    AddInHandler()
    {
    }

    public static AddInHandler Instance
    {
        get { return instance.Value; }
    }

    public async Task<AvailableActions> GetAvailableActions(string carrierMnemonic)
    {
        // some code that uses await...
    }
}

如果我尝试通过单例使用异步方法,例如:

public async Task<Collection<CarrierInformation>> RetrieveAvailableCarriersAsync()
{
    // some await code here

    await Task.Run(() => 
    {
        // ...
        var availableActions = await AddInHandler.Instance.GetAvailableActions(addIn.Name);
    }
}

然后我就报错了。

The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

我预计是因为实例 属性 不是异步的,所以我遇到了这个问题?这是否正确,是否有推荐的解决此问题的最佳方法?

I'm expecting it's because the Instance property isn't async that I'm having this issue?

不,您只是在 lambda 表达式声明中缺少 async 修饰符。 lambda 本身必须标记为 async 以便编译器在其中使用 await

await Task.Run(async () => 
{
    // ...
    var availableActions = await AddInHandler.Instance.GetAvailableActions(addIn.Name);
}

The documentation 非常简单:

Use the async modifier to specify that a method, lambda expression, or anonymous method is asynchronous. If you use this modifier on a method or expression, it's referred to as an async method.

如果你打电话给

var availableActions = await AddInHandler.Instance.GetAvailableActions(addIn.Name);

在类型为 new Action(() =>{}); 的表达式中,则需要 async 修饰符。

new Action( async () =>
   {
      // some await code
   });