Control.Invoke 在第二次调用时失败
我正在使用 .Net Compact Framework 2.0 SP2 和 C# 开发Windows Mobile 5.0 及更高版本应用程序。
我在一个方法中有这段代码:
if (listBox1.InvokeRequired)
{
Invoke(new MethodInvoker(
delegate() { listaBox1 = listaBox2; listBox1.Visible = true; }));
}
else
{
listBox1 = listBox2;
listBox1.Visible = true;
}
当我运行它时,它在第二条语句(listBox1.Visible = true;)上抛出异常,说:
Control.Invoke 必须用于与在单独线程上创建的控件进行交互。< /em>
发生了什么事?
I'm developing a Windows Mobile 5.0 and above application with .Net Compact Framework 2.0 SP2 and C#.
I have this code inside a method:
if (listBox1.InvokeRequired)
{
Invoke(new MethodInvoker(
delegate() { listaBox1 = listaBox2; listBox1.Visible = true; }));
}
else
{
listBox1 = listBox2;
listBox1.Visible = true;
}
When I run it, it throws an exception on second statement (listBox1.Visible = true;) saying:
Control.Invoke must be used to interact with controls created on a separate thread.
What's happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的两个列表框是在不同的线程上创建的。几乎在所有情况下,这都是一个非常非常糟糕的主意。
Your two ListBoxes were created on different threads. That is, in almost all cases, a really, really bad idea.
原因是在这种情况下有 2 个
ListBox
引用您只检查了 listBox1 的 InvokeRequired 成员。然而,您实际上最终在 listBox2 最初指向的实例上调用 .Visible 。根据结果行为,这 2 个引用最初可能指向
ListBox
的 2 个不同实例。要解决此问题,请检查 listBox2 上的 InvokeRequired,因为这是您最终实际使用的。
The reason why is there are 2
ListBox
references in this scenarioYou only checked the InvokeRequired member for listBox1. Yet you actually end up calling .Visible on the instance originally pointed to by listBox2. Based on the resulting behavior, it's likely that the 2 references originally pointed to 2 different instances of
ListBox
.To fix this, check the InvokeRequired on listBox2 since that's the one you actually end up using.