表单的C#形式在单独的线程上 [英] C# Form of a form is on separate thread

查看:56
本文介绍了表单的C#形式在单独的线程上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题.

我有3种形式.form1,form2,form3.

I have 3 forms. form1, form2, form3.

form1是开始/主要形式.在form1中,我有代码:

form1 is starting/main form. in form1 I have code:

form2 f2 = new form2;
f2.ShowDialog();

form2打开,我不能专注于foorm1,它们都在同一线程上.就是我想要的.

form2 opens, I can't focus on foorm1, they are both on the same thread. Just what I want.

在form2上,我有代码:

On form2 I have code:

form3 f3 = new form3;
DialogResult result = f3.ShowDialog();

我运行此代码,然后...对于某些我来说未知的原因,这个form3在新线程上运行,我可以专注于form2.我不希望这种情况发生.我不知道为什么这个form3在新线程上运行.我无法使用DialogResult,因为它会导致错误(跨线程).

I run this code and... For some, unknown for me reason this form3 runs on new thread and I can focus on form2. I don't want this to happen. I have no idea why this form3 runs on new thread. I can't use DialogResult because it leads to error (Cross-thread).

它的行为就像我正在使用f3.Show(),但我正在使用f3.ShowDialog();

It behaves as if I was using f3.Show() but I'm using f3.ShowDialog();

比你提前

P.S.

如果我使用

form3 f3 = new form3;
DialogResult result = f3.ShowDialog(this);

我知道了:

System.InvalidOperationException原为用户代码未处理
消息=没有跨线程操作有效:从线程不是原来的线程创建于.

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

在此行:

DialogResult result = f3.ShowDialog(this);

推荐答案

对话框功能通过实现自己的消息循环来实现.由于两个线程都有处理消息的消息循环,因此您启用了两个对话框.手动禁用第一个对话框,或者从同一线程创建并显示所有对话框.我强烈建议您在一个线程中完成所有用户界面.请参阅InvokeRequired和Invoke控件的成员.

Dialogs function by implementing their own message loop. Since both threads have a message loop processing messages, you have two dialogs enabled. Either manually disable the first dialog or create and show all dialogs from the same thread. I would strongly recommend that you do all the UI in a single thread. Please see the InvokeRequired and Invoke members of Control.

这篇关于表单的C#形式在单独的线程上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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