【问题标题】:controls doesn't show if run on a background thread ( c# winform)如果在后台线程上运行,控件不显示(c#winform)
【发布时间】:2013-02-15 16:27:14
【问题描述】:

我有一个带有多个控件的表单(代码中的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());

}

【问题讨论】:

  • 如果您使用多个thread,为什么要将ApartmentState 设置为单线程([STAThread] 和ApartmentState.STA)?
  • 你想达到什么目的? var complexUI = new complexForm();// this takes long time to loadcomplexForm 构造函数中的什么操作导致长加载?
  • 实际上我有 DevExpress richeditcontrols 和ribbonbar,需要很长时间才能加载。请参考此网址devexpress.com/Support/Center/p/Q406398.aspx
  • 在另一个线程上显示 UI 需要泵送消息循环。 Application.Run() 是必需的。

标签: c# multithreading winforms


【解决方案1】:

不要这样做。会以泪水收场。仅从 UI 线程创建 UI 控件 - 这是拥有消息泵的线程,这对于正确操作至关重要。

解决这个问题的正确方法是创建一个启动画面,它会在您的主窗口初始化时显示。

Stack Overflow 上有很多关于如何创建启动画面的帖子。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多