如果在后台线程上运行,则控件不显示(c# winform) [英] controls doesn't show if run on a background thread ( c# winform)
问题描述
我有一个包含多个控件的表单(代码中的complexForm),加载需要一些时间.所以我决定放入一个单独的线程以减少初始加载时间.一切正常,除了等待表单上的标签控件(代码中的 Form1)最初没有显示;就在 Form1 熄灭前一秒.所以我的问题是,为什么标签控件不显示?
I have a form (complexForm in the code) with multiple controls which takes some time to load. So I decided to put in in a separate thread in order to decrease initial loading time. Everything works fine except the label control on the wait form ( Form1 in the code) doesn't show up initially; just a flash of a sec before Form1 went off. So my question is, why doesn't the label control show up?
[STAThread]
static void Main()
{
Thread thread = new Thread(delegate()
{
var wait = new Form1(); //simple form with a label control with text "please wait"
wait.Show();
var complexUI = new complexForm();// this takes long time to load
wait.Dispose();// it will go off even without this method
// MessageBox.Show("loaded");
});
thread.SetApartmentState(ApartmentState.STA);
thread.Priority = ThreadPriority.Highest;
thread.IsBackground = true;
thread.Start();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new main());
}
推荐答案
不要这样做.它会以泪水结束.仅从 UI 线程创建 UI 控件 - 这是拥有消息泵的线程,这对于正确操作至关重要.
Do not do this. It'll end in tears. Only ever create UI controls from the UI thread - that's the thread that owns the message pump, which is crucial to proper operation.
正确的解决方案是创建一个在主窗口初始化时显示的启动画面.
The right solution to this is to create a Splash Screen which is shown while your main window is initialising.
Stack Overflow 上有很多关于如何创建启动画面的主题.
There's quite a few threads on Stack Overflow about how to create a splash screen.
这篇关于如果在后台线程上运行,则控件不显示(c# winform)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!