bretddog
bretddog

Reputation: 5529

How to get multi-thread response from WebClient DownloadDataAsync, (or alternative)?

For downloading a number of images I'm making DownloadDataAsync calls to separate instances of WebClient, in a loop, with a thread sleep delay. I expected the response to happen on separate threads, but it seems not, as response only occurs after all calls are completed.

So what's an appropritate fix for this? Is there an alternative client type, or should I make a thread for each webclient call?

So currently I'm calling this in a loop:

 Private Sub StartDownload(ByVal webImageLink As String, ByVal token As Object)
    Dim wc As New WebClient
    Try
        AddHandler wc.DownloadDataCompleted, AddressOf OnDownloadCompleted

        wc.DownloadDataAsync(New System.Uri(webImageLink), token)

        Threading.Thread.Sleep(delay)

    Catch ex As Exception
        Debug.Print("Exception in ImageDownloader.DoDownload ")
    End Try
End Sub

Upvotes: 0

Views: 1121

Answers (1)

Hans Passant
Hans Passant

Reputation: 942099

Feature, not a bug. WebClient makes an effort to raise the DownloadCompleted event on the same thread, if it can. It can when you call it from the UI thread of a Winforms or WPF application. Which is usually desirable, you can update the UI in the completion event handler without having to use Control/Dispatcher.BeginInvoke(). But with the side-effect that this won't happen until your code stops running so the event handler can be called. It is dispatched by the UI thread's dispatch loop.

A workaround, if you really need one, is to start the downloads with a little helper method that you start with ThreadPool.QueueUserWorkItem() or a Thread.

Upvotes: 1

Related Questions