控件不';t显示是否在后台线程上运行(c#winform)

本文关键字:线程 后台 运行 c#winform 是否 显示 控件 | 更新日期: 2023-09-27 17:59:27

我有一个带有多个控件的表单(代码中的complexForm),它需要一些时间才能加载。所以我决定放入一个单独的线程,以减少初始加载时间。除了等待表单上的标签控件(代码中的Form1)最初没有显示外,一切都很好;就在Form1爆炸前一秒钟。所以我的问题是,为什么标签控件没有出现?

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

控件不';t显示是否在后台线程上运行(c#winform)

不要这样做。它将以眼泪结束。只能从UI线程创建UI控件——这是拥有消息泵的线程,这对正确操作至关重要。

正确的解决方案是创建一个启动屏幕,在主窗口初始化时显示。

Stack Overflow上有很多关于如何创建启动屏幕的线程。