我想我該如何解決它我調試錯誤沒有CheckForIllegalCrossThreadCalls = false 我知道,這是一件壞事,所以我該如何修復我的代碼?這裏有一個例子:CheckForIllegalCrossThreadCalls不是一個選項
Private Sub tim1_Tick(sender As Object, e As EventArgs) Handles tim1.Tick
BackgroundWorker1.RunWorkerAsync()
end sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim inStream As StreamReader
Dim webRequest As WebRequest
Dim webresponse As WebResponse
webRequest = webRequest.Create("https://website.com/stuff=100&id=" + ListBox2.Text)
DirectCast(webRequest, HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729; .NET4.0E)"
webresponse = webRequest.GetResponse()
inStream = New StreamReader(webresponse.GetResponseStream())
TextBox5.Text = inStream.ReadToEnd()
For Each m As Match In New Regex("""(?<=href="")([^""]+)").Matches(TextBox5.Text)
ListBox1.Items.Add(m.Value + "@website.com,")
Next
Try
correct()
Catch ex As Exception
End Try
For index = Me.ListBox2.Items.Count - 1 To 1 Step -1
If Me.ListBox2.FindStringExact(Me.ListBox1.GetItemText(Me.ListBox2.Items(index))) <> index Then
Me.ListBox2.Items.RemoveAt(index)
End If
Next
For index = Me.ListBox1.Items.Count - 1 To 1 Step -1
If Me.ListBox1.FindStringExact(Me.ListBox1.GetItemText(Me.ListBox1.Items(index))) <> index Then
Me.ListBox1.Items.RemoveAt(index)
End If
Next
Label1.Text = ListBox1.Items.Count
end sub
錯誤消息:
An exception of type 'System.InvalidOperationException' occurred in
System.Windows.Forms.dll but was not handled in user code
Additional information: Cross-thread operation not valid:
Control 'ListBox2' accessed from a thread other than the thread it was created on.
If there is a handler for this exception, the program may be safely continued.
的問題部分:webRequest = webRequest.Create("https://www.facebook.com/plugins/fan.php?connections=100&id=" + ListBox2.Text)
我看到在後臺線程訪問GUI對象(ListBox1中)。那就是問題所在。你需要將這些信息提供給gui線程。不要使用空的try-catch塊。例外信息是你的朋友,不要忽視它。 – LarsTech 2014-12-02 18:18:52
@LarsTech - 也可以訪問'TextBox5'! – 2014-12-03 14:42:05