这两个调用有何不同? [英] How are these two invocations different?

查看:77
本文介绍了这两个调用有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改WinForms应用程序上的组合框,但出现了一些奇怪的现象.我正在尝试两种方法:

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;
}

我正在尝试两种不同的方法来从GUI线程调用此方法.这一项有效:

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);
    }
}

这会引发TargetInvocationException:

And this throws a TargetInvocationException:

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

我更喜欢使用第二个,因为它更清晰,但是我不完全确定为什么当第一个示例运行良好时它会引发错误.第一个示例调用modifyCombo方法并正确返回对象的IndexOf.第二个示例从IndexOf返回-1.

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.

这是stacktrace的pastebin链接. http://pastebin.com/TwfUDw4u

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

推荐答案

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

顺便说一句.优良作法是在使用Invoke之前测试(this.IsHandleCreated&!this.IsDisposed).

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

这篇关于这两个调用有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆