How are these two invocations different?

2019-09-02 20:41发布

问题:

I'm trying to modify a combo box on my WinForms application, and I'm getting some strange behavior. I'm trying two methods:

Here is the method I need to invoke:

private void modifyCombo(ClassInfoHolder oldClass, ClassInfoHolder newClass) {
    this.monitoredComboBox.Items[monitoredComboBox.Items.IndexOf(oldClass)] = newClass;
}

I'm trying two different ways to invoke this method from the GUI thread. This one works:

delegate void modifyComboCollection(ClassInfoHolder oldClass, ClassInfoHolder newClass);

private void modifySecondTabComboBox(ClassInfoHolder oldClass, ClassInfoHolder newClass) {
    if (monitoredComboBox.InvokeRequired) {
        modifyComboCollection m = new modifyComboCollection(modifyCombo);
        this.BeginInvoke(m, oldClass, newClass);
    } else {
        // no need for Invoke
        modifyCombo(oldClass, newClass);
    }
}

And this throws a TargetInvocationException:

this.BeginInvoke(new Action(() => {
    modifyCombo(oldClass, newClass);
}));

I'd prefer to use the second because it's much clearer, but I'm not entirely sure why it throws an error when the first example works just fine. The first example calls the modifyCombo method and correctly returns the IndexOf of the object. The second example is returned -1 from IndexOf.

Edit: Here is a pastebin link of the stacktrace. http://pastebin.com/TwfUDw4u

回答1:

this.BeginInvoke(m, new[] {oldClass, newClass});

BTW. Good practice is to test if (this.IsHandleCreated && !this.IsDisposed) before use Invoke.