Hello
This is a newbie question. I'm using VB 2010 Express and need to write a small application to download a few web pages.
To avoid freezing the UI, I use WebClient asynchronously, but the application fails because WebClient cannot handle more than one download simultaneously:
What would be the right way to perform this? Should I use some kind of semaphore to force WebClient to wait in the ForEach loop, or should I use another technique?
Thank you.
This is a newbie question. I'm using VB 2010 Express and need to write a small application to download a few web pages.
To avoid freezing the UI, I use WebClient asynchronously, but the application fails because WebClient cannot handle more than one download simultaneously:
Code:
Imports System.Net
Imports System.IO
Public Class Form1
Private Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
If e.Cancelled = False AndAlso e.Error Is Nothing Then
RichTextBox1.Text = CStr(e.Result)
RichTextBox1.Refresh()
Button1.Enabled = True
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
Dim webClient As New WebClient
AddHandler webClient.DownloadStringCompleted, AddressOf AlertStringDownloaded
Dim theaters As New Dictionary(Of String, String)
theaters.Add("Theater #1", "http://www.theaters.com/1.html")
theaters.Add("Theater #2", "http://www.theaters.com/2.html")
For Each kvp As KeyValuePair(Of String, String) In theaters
Me.Text = kvp.Key
'ERROR: WebClient does not support concurrent I/O operations.
webClient.DownloadStringAsync(New Uri(kvp.Value))
Next
End Sub
End Class
Thank you.