littlebigman
Well-known member
- Joined
- Jan 5, 2010
- Messages
- 75
- Programming Experience
- Beginner
Hello
I noticed something strange when using WebClient.DownloadStringAsync in a loop to download several web pages: In each iteration, I add the URL in a ListBox, proceed to call DownloadStringAsync(), wait for a shared string to be filled with the web page, use a regex to extract its Title, update a RichTextBox with this, and then loop back to the next URL to fetch.
The odd thing, is that the ListBox is already showing the next URL although the program hasn't yet updated the RichTextBox :-/ How can I tell the loop to wait until the RTB is refreshed?
Here's the code:
Thank you for any help.
I noticed something strange when using WebClient.DownloadStringAsync in a loop to download several web pages: In each iteration, I add the URL in a ListBox, proceed to call DownloadStringAsync(), wait for a shared string to be filled with the web page, use a regex to extract its Title, update a RichTextBox with this, and then loop back to the next URL to fetch.
The odd thing, is that the ListBox is already showing the next URL although the program hasn't yet updated the RichTextBox :-/ How can I tell the loop to wait until the RTB is refreshed?
Here's the code:
VB.NET:
Imports System.Net
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Shared page As String
Public Shared Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
If e.Cancelled = False AndAlso e.Error Is Nothing Then
page = CStr(e.Result)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim title As Regex = New Regex("<title>(.+?)</title>")
Dim m As Match
Dim webClient As New WebClient
AddHandler webClient.DownloadStringCompleted, AddressOf AlertStringDownloaded
Dim URLArray As New ArrayList
URLArray.Add("http://www.google.com")
URLArray.Add("http://www.yahoo.com")
[COLOR="Blue"]'Why delay between update of ListBox and RichTextBox?[/COLOR]
Dim URL As String
For Each URL In URLArray
ListBox1.Items.Add("Downloading " & URL)
ListBox1.Refresh()
page = Nothing
webClient.DownloadStringAsync(New Uri(URL))
[COLOR="blue"]'Better way to wait until page has been downloaded?[/COLOR]
While page Is Nothing
Application.DoEvents()
End While
'Use regex to extract bits of infos, and save them into SQLite
m = title.Match(page)
If m.Success Then
RichTextBox1.AppendText(m.Groups(1).Value & vbCrLf)
RichTextBox1.Update()
End If
[COLOR="blue"]'At this point, why is ListBox already updated with next URL?[/COLOR]
Next
Button1.Enabled = True
End Sub
End Class
Thank you for any help.