【问题标题】:Function to Call Async Sub finishing Function Before Async异步之前调用异步子整理函数的函数
【发布时间】:2016-12-30 18:43:52
【问题描述】:

在 DLL 中使用 HttpClient sub。但是调用应用程序希望得到一个 True 或 False 作为 HttpClient 工作的返回值。

所以我试着写一个像这样的简单调用应用程序

 Public Function SendBasket() As Integer
    Try
        SendMarketBasket()

        If MktResp = "Loaded" Then
            Return 0
        ElseIf MktResp = "Nothing to Load" Then
            Return -1
        End If
    Catch ex As Exception
        Return -1
    End Try
End Function

Private Async Sub SendMarketBasket()........

显然,调用 Async 调用之后的 If 语句在设置 MktResp 之前立即运行。怎样才能在Async调用完成后才返回函数结果?

TIA 哈利

【问题讨论】:

  • 我不认为有任何方法可以判断 Async Sub 何时完成 - 它们是一劳永逸的。您可以将其更改为 Private Async Function SendMarketBasket() As Task 并使用 SendMarketBasket().Wait() 但这可能会死锁。 This 有一些很好的信息,可能还有其他信息。

标签: vb.net async-await httpclient


【解决方案1】:

将您的 SendMarketBasket 方法更改为返回 Task
然后您可以“等待”任务完成并根据返回的结果继续执行您的代码

Private Async Function SendMarketBasketAsync() As Task
    ' your code
End Function

那么你也需要将SendBasket方法的签名改为异步。

Public Async Function SendBasketAsync() As Task(Of Integer)
    Await SendMarketBasketAsync()

    If MktResp = "Loaded" Then
        Return 0
    ElseIf MktResp = "Nothing to Load" Then
        Return -1
    End If
End Function

如果您将Async 后缀添加到异步方法,它将节省您和您的同事的时间。

Async 就像僵尸,如果你开始在某个地方使用它,它会蔓延到你的所有应用程序 - 这不是一件坏事 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 2015-01-22
    • 2019-01-20
    • 2020-04-20
    • 1970-01-01
    • 2013-07-12
    • 2013-03-28
    • 2018-12-13
    相关资源
    最近更新 更多