我们可以在构造函数中调用 await 吗?

Can we call await in constructor?

Shared Sub New()
    'Await setAllAccountsAsync()
    SetAllAccounts()
End Sub

这个有效

然而,

Shared Sub New()
    Await setAllAccountsAsync()
    'SetAllAccounts()
End Sub

不会

Shared async Sub New()
    Await setAllAccountsAsync()
    'SetAllAccounts()
End Sub

也不行

然而

Private Shared Async Sub SetAllAccounts()
    Await setAllAccountsAsync()
End Sub

工作正常。

所以我们可以 return 在异步中作废,但我们不能在构造函数中这样做。为什么?这是真的吗?

注:

我实际上不希望它成为构造函数。注意到它是共享的新的而不是新的。我只想让一些代码成为 运行 一次。例如,在我的例子中,初始化程序会上网并找到所有交易对并将交易对存储在私有变量中。我希望在使用 class 之前完成。

setAllAccountsAsync 的内容如下

Private Async Function initializeAsync() As Task
    _marketid = Await CookieAwareWebClient.downloadString1Async("https://www.coinexchange.io/api/v1/getmarkets")
End Function

Is this true?

是的。

Why?

Async Sub(或 async void)方法已添加到 C# 和 VB,以便事件处理程序可以是异步的。在所有其他情况下,您应该避免使用 Async Sub。具体来说,Async Sub 不是实现构造函数的有效方法。

构造函数不能是异步的,语言很可能在可预见的未来保持这一原则。如果你需要异步构造一个实例,你应该使用工厂方法,即 returns Task(Of T) 的静态方法,无论你的类型是 T 。我的 blog post on async constructors.

中描述了更多详细信息和替代方法