Friday, October 9, 2009

InvalidOperationException: Cross-thread operation not valid: Control ‘Form1’ accessed from a thread other than the thread it was created on.

When I first time met with this error, it was caused by an update of a windows form control from a separate thread.

Here is the workaround.

// delegation to cross the thread boundary
private delegate void AddComboBoxItemDelegate(object item);

private void AddComboBoxItem(object item)
{
  if (this.comboBox1.InvokeRequired) {
    // Invoke delegate so that the main UI thread is able to update the controls in the form
this.comboBox1.Invoke(new AddComboBoxItemDelegate(this.AddComboBoxItem), item);
  }
  else {
    this.comboBox1.Items.Add(item);
  }
}



Hope this helps. Cheers!
 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template