Control.Invoke 在第二次调用时失败

发布于 2024-08-13 08:18:04 字数 519 浏览 1 评论 0原文

我正在使用 .Net Compact Framework 2.0 SP2C# 开发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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

↙温凉少女 2024-08-20 08:18:04

您的两个列表框是在不同的线程上创建的。几乎在所有情况下,这都是一个非常非常糟糕的主意。

Your two ListBoxes were created on different threads. That is, in almost all cases, a really, really bad idea.

携余温的黄昏 2024-08-20 08:18:04

原因是在这种情况下有 2 个 ListBox 引用

  1. listBox1
  2. listBox2

您只检查了 listBox1 的 InvokeRequired 成员。然而,您实际上最终在 listBox2 最初指向的实例上调用 .Visible 。根据结果​​行为,这 2 个引用最初可能指向 ListBox 的 2 个不同实例。

要解决此问题,请检查 listBox2 上的 InvokeRequired,因为这是您最终实际使用的。

The reason why is there are 2 ListBox references in this scenario

  1. listBox1
  2. listBox2

You 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文