开发者

Background worker problem [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Cross-thread operation not valid

Hi, I am testing a background workder. I am running the following code for the test.

Private Sub bgwTest_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwTest.DoWork
   Dim a As Integer = 0
   Do While a < 10 'Infinite loop
       ComboBox1.Items.Add(1)
   Loop

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, 开发者_高级运维ByVal e As System.EventArgs) Handles MyBase.Load
   PictureBox1.Visible = True &#39;Contains my animated GIF

'Purpose is GIF keeps looping (it is animated GIF) despite computer is stuck in infinite loop bgwTest.RunWorkerAsync() End Sub

But this code generates the following error:

"Cross-thread operation not valid: Control 'ComboBox1' accessed from a thread other than the thread it was created on."

Please help. Thanks Furqan


You should not modify GUI elements on non-GUI threads. All modifications to textboxes, comboboxes, labels, etc.. should be done on the main thread. In the case of a BackgroundWorker that would be inside the RunWorkerCompleted and ProgressChanged events.

So inside the DoWork event you could fill some data structure (a list for example) with calculated values and in the RunWorkerCompleted event read this structure and update the combobox.


You cannot access controls from another thread, you need to use delegates to achieve this.

Further reading on the matter is here:

http://msdn.microsoft.com/en-us/library/ms171728.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜