2016-12-30 57 views
0

在DLL中使用HttpClient sub。但是调用应用程序想要得到一个True或False作为HttpClient工作的回报。函数调用Async Sub精修函数在Async之前

于是,我就写像这样

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()........ 

一个简单的调用应用程序显然MktResp设置之前调用异步调用后,如果语句运行。如何才能在Async调用完成后返回函数结果?

TIA 哈利

+0

我不认为有任何方式告诉了'异步Sub当'完成 - 他们是忘却火。您可以将其更改为'Private Async Function SendMarketBasket()As Task'并使用'SendMarketBasket()。Wait()',但这可能会导致死锁。 [这](http://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c)有一些很好的信息,并可能有其他人。 – Mark

回答

2

更改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像僵尸,如果你开始使用它的地方,将遍布所有应用程序 - 这是不是一件坏事:)

相关问题