I must be doing something wrong since this code is blocking and runs synchronously, inspite of calling the async
method of GetStringAsync
. Any help would really help me understand the reasons:
Private Async Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
Dim urls As List(Of String) = SetUpURLList()
Dim baseAddress = New Uri("http://www.amazon.com")
ServicePointManager.DefaultConnectionLimit = 10
Dim requestNumber As Integer = 0
For Each url In urls
requestNumber += 1
Console.WriteLine("Request #:{0}", requestNumber)
Dim cookies As New CookieContainer()
Dim handler As New HttpClientHandler With {.CookieContainer = cookies, _
.UseCookies = True}
Dim httpClient = New HttpClient(handler) With {.BaseAddress = baseAddress}
Dim response As String = Await HttpClient.GetStringAsync(url).ConfigureAwait(False)
For Each cook As Cookie In cookies.GetCookies(baseAddress)
Console.WriteLine(cook.Name & "=" & cook.Value)
Next
httpClient.Dispose()
Next
Console.WriteLine("Done")
End Sub
Here is the complete working code now - thx to @l3arnon for fire all and wait up on all completion.
Your code isn't blocking, it's just sequential. You are firing each
Async
operation and asynchronously waiting for it to complete withAwait
before starting the next one.If you want to fire all these operations concurrently first create a task for each
url
and thenAwait
all these tasks at once usingTask.WhenAll
:*I hope this code makes sense, since I'm not really familiar with VB.Net.