1

Using HttpClient sub in a DLL. But the calling app wants to get a True or False as a return that the HttpClient worked.

So I tried to write a simple calling app like so

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

Obviously the If statement after the call to the Async call runs immediately before the MktResp is set. How can I return the function result only after the Async call completes?

TIA Harry

LightStamp
  • 39
  • 7
  • I don't think there is any way to tell when an `Async Sub` completes - they are fire-and-forget. You could change it to `Private Async Function SendMarketBasket() As Task` and use `SendMarketBasket().Wait()` but that may deadlock. [This](http://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c) has some good info, and there are probably others. – Mark Dec 30 '16 at 20:43

1 Answers1

3

Change your SendMarketBasket method to return Task.
Then you can "await" for task get completed and continue execution your code based on the returned result

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

Then you need change signature of SendBasket method to asynchronous too.

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

If you add Async suffix to the asynchronous methods it will save your and your colleagues time.

Async is like zombie if you start using it somewhere it will spread over all of your application - this is not a bad thing :)

Fabio
  • 31,528
  • 4
  • 33
  • 72