How are these two invocations different?

∥☆過路亽.° 提交于 2019-12-11 17:56:53

问题


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.



来源:https://stackoverflow.com/questions/4269463/how-are-these-two-invocations-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!