2014-12-02 9 views
0

我想我該如何解決它我調試錯誤沒有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)

+1

我看到在後臺線程訪問GUI對象(ListBox1中)。那就是問題所在。你需要將這些信息提供給gui線程。不要使用空的try-catch塊。例外信息是你的朋友,不要忽視它。 – LarsTech 2014-12-02 18:18:52

+0

@LarsTech - 也可以訪問'TextBox5'! – 2014-12-03 14:42:05

回答

1

取而代之的響應流保存到TextBox5.Text,將其保存在e.Result

e.Result = inStream.ReadToEnd() 

移動該點後的代碼int o BackgroundWorker1.RunWorkerCompleted的處理程序。這將在UI線程上運行,並且可以在那裏對UI進行更新。

還需要在被在DoWork(例如ListBox2.Text)使用的任何UI信息作爲參數傳遞:

BackgroundWorker1.RunWorkerAsync(ListBox2.Text) 
+0

如果我把我的代碼放到BackgroundWorker1.RunWorkerCompleted,那麼我的UI就會凍結。 – sandor 2014-12-02 18:42:12

+0

@sandor在該定時器上設置的時間間隔是多少? – LarsTech 2014-12-02 18:43:24

+0

1000毫秒。你爲什麼問? – sandor 2014-12-02 18:54:22

相關問題