0

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

Community
  • 1
  • 1
Furqan Sehgal
  • 4,917
  • 33
  • 108
  • 167
  • you should try using the search feature of SO at least once with keywords pertaining to your issue. Even google might help. – deostroll May 30 '11 at 11:48
  • Hi. In the case of compiler or runtime errors, it's a good idea to copy the relevant parts of the error message into the title of the question, as then you would get all the existing duplicates on the subject present on SO. Here's a bunch: http://stackoverflow.com/search?q=cross+thread - I'm closing this question as a duplicate, we really don't need more of these questions here now. – Lasse V. Karlsen May 30 '11 at 17:53

2 Answers2

2

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

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

Tom Pickles
  • 890
  • 10
  • 26