【问题标题】:ToolTip causes cross thread operation?ToolTip 导致跨线程操作?
【发布时间】:2013-12-11 13:15:43
【问题描述】:

帮助我理解这一点。我正在调试一些旧代码。反正我有这个方法:

    private void textBox1_Validated(object sender, EventArgs e)
    {
        toolTip1.SetToolTip(textBox1, "This is a test tooltip");
        toolTip1.Show("This is a test tooltip", this, label3.Location, 2000);
    }

此方法按预期工作,它在成功验证后立即显示一个工具提示。这一切都发生在 MDI 应用程序的子窗体上。如果我之后尝试关闭表单(无论 tooltop 是否可见),我都会收到此错误:

跨线程操作无效:从 线程不是创建它的线程 System.Windows.Forms.Control.get_Handle() 在 System.Windows.Forms.Control.SetParentHandle(IntPtr 值)在 System.Windows.Forms.Control.ControlCollection.Remove(控制值)
在 System.Windows.Forms.MdiClient.ControlCollection.Remove(控制 值)在 System.Windows.Forms.Control.Dispose(布尔处理)
在 System.Windows.Forms.Form.Dispose(Boolean disposing) 在 VlastitiBackgroundWorker.BazniEkran.Dispose(Boolean disposing) in D:\TFSWorkspace\VlastitiBackgroundWorker\VlastitiBackgroundWorker\BazniEkran.Designer.cs:line 20 在 VlastitiBackgroundWorker.DesetSekundi.Dispose(布尔 处置)在 D:\TFSWorkspace\VlastitiBackgroundWorker\VlastitiBackgroundWorker\DesetSekundi.Designer.cs:line 20 在 System.ComponentModel.Component.Dispose() 在 System.Windows.Forms.Form.WmClose(Message&m)

为什么?它是可重现的。

【问题讨论】:

  • 你确定是这段代码吗?
  • 何时调用textBox1_Validated
  • 可能是您尝试从 BackgroundWorker 访问您的控件
  • 您的 Background Worker 组件似乎正在访问您的 TestForm (this) 实例。
  • 是的,我确定。如果我注释掉这两行代码,我将不会收到此错误。从 Validated 事件调用 Validated 方法。该项目不包含任何多线程操作。

标签: c# .net winforms


【解决方案1】:

试试这个

private void textBox1_Validated(object sender, EventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                toolTip1.SetToolTip(textBox1, "This is a test tooltip");
                toolTip1.Show("This is a test tooltip", this, label3.Location, 2000);
            });
        }

【讨论】:

  • 您是在单独的线程中创建 toolTip1 吗?尝试使用 toolTip1.Invoke() 方法,它将在 toolYip1 创建的线程上运行
【解决方案2】:

经过进一步调查,我发现如果我从 Syncfusion 禁用 TabbedMDIManager 第三方组件,此错误就会消失。我使用这个组件使我的 MDI 子窗体看起来像 VisualStudio 一样的选项卡。

现在我不知道这个组件和这个事件方法之间的联系是什么,但很明显我需要做更多的调查并可能联系 Syncfusion 支持。

感谢您的帮助。

【讨论】:

  • 您应该在问题的第一段中包含信息。第三方组件显着改变了方程式。
  • 我不同意。软件一直使用第三方组件,如果每次有人遇到问题都会列出他们正在使用的所有第三方库,stackoverflow 将变得难以使用
【解决方案3】:
//Use Invoke or BeginInvoke on the control itself for cross threading manipulation..

            private void textBox1_Validated(object sender, EventArgs e)
            {
                toolTip1.Invoke((MethodInvoker)delegate
                {
                    toolTip1.SetToolTip(textBox1, "This is a test tooltip");
                    toolTip1.Show("This is a test tooltip", this, label3.Location, 2000);
                });
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-19
    • 2012-04-26
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多