gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:22:27 25 4
gpt4 key购买 nike

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

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.

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

最佳答案

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.

关于c# - 在 Singleton.Instance 后面调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com