Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c# - Cross-thread exception when setting WinForms.Form owner - how to do it right?

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

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;

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

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

How am I supposed to do it right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...