设置WinForms.Form所有者时出现跨线程异常-如何正确处理? [英] Cross-thread exception when setting WinForms.Form owner - how to do it right?

查看:124
本文介绍了设置WinForms.Form所有者时出现跨线程异常-如何正确处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主UI线程,该线程运行应用程序并创建主窗口表单(我们称其为W).我还有一个辅助线程,可以旋转并创建一个对话框(我们称其为B).

I have a main UI thread which runs the application and creates the main window form (let's call it W). I have also a secondary thread that I spin up and which creates a dialog box (let's call it B).

我想将对话框B的所有者设置为主窗口W. B所有者的设置发生在创建B的线程上.基本上:

I want to set the owner of the dialog B to be the main window W. The setting of Bs owner happens on the thread that created B. Basically:

b.Owner = w;

但这会引发跨线程异常,告诉我我正在尝试从错误的线程访问W对象.

but this throws a cross-thread exception telling me that I am tryng to access the W object from the wrong thread.

因此,我尝试通过在W上使用Control.Invoke在主UI线程上执行代码.但是然后,我遇到了同样的错误,告诉我我正在尝试从错误的线程访问B:

So I tried to execute the code on the main UI thread, by using a Control.Invoke on W. But then, I get the same error telling me that I am trying to access B from the wrong thread:

System.InvalidOperationException was unhandled by user code
  Message=Cross-thread operation not valid: Control 'B' accessed from a
  thread other than the thread it was created on.
  Source=System.Windows.Forms

我应该怎么做正确?

推荐答案

这是Winforms中的一个错误,Windows实际上支持使所有者成为在另一个线程上创建的窗口.有一种方法可以禁用该检查,您应该从不这样做.除非您必须这样做:

It's a bit of a bug in Winforms, Windows actually supports making the owner a window that was created on another thread. There's a way to disable that check, something you should never do. Except when you have to I suppose:

    private void button1_Click(object sender, EventArgs e) {
        var t = new Thread(() => {
            Control.CheckForIllegalCrossThreadCalls = false;
            var frm = new Form2();
            frm.Show(this);
            Control.CheckForIllegalCrossThreadCalls = true;
            Application.Run(frm);
        });
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

不知道这是否是100%安全的,可能是Winforms交互将事情搞砸了.您在这里未经测试的水域中,出没了许多穿线鲨鱼.

I do not know if this is 100% safe, there could be a Winforms interaction that screws things up. You are in untested waters here, infested with threading sharks.

这篇关于设置WinForms.Form所有者时出现跨线程异常-如何正确处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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