Search code examples
c#multithreadingcomboboxinvoke

Why is combobox throwing exception even though invoke is used


I am trying to set the selected item of a combobox from another thread but the software is throwing an Exception with the message "Cross-thread operation not valid. Control xxx accessed from a thread other than the thread it was created"

I already tried to use a MethodInvoker if InvokeRequired is true on the ComboBox, but I am still getting the Exception.

public class ComboBoxAdapter
{
    System.Windows.Forms.ComboBox comboBox;     

    //...

    public void setSelectedItem( object item ) {
        if ( comboBox.InvokeRequired )
            comboBox.Invoke( new MethodInvoker( () => setSelectedItem( item ) ) );

        comboBox.SelectedItem = item;
    }
}

I do not expected an exception if I am accessing the ComboBox like in my code.


Solution

  • You miss an else

    public void setSelectedItem( object item ) {
        if ( comboBox.InvokeRequired )
            comboBox.Invoke( new MethodInvoker( () => setSelectedItem( item ) ) );
        else
            comboBox.SelectedItem = item;
    }
    

    otherwise you direct update the control even when Invoke is Required.