【问题标题】:C# Open Form in a new Thread or Task?C# 在新线程或任务中打开表单?
【发布时间】:2018-05-06 10:10:26
【问题描述】:

如何在 C# 中使用线程或任务打开新表单。

示例:

public void openform()
{
    Form _form = new Form();
    _form.show()
}

Thread _thread = new Thread(openform);
_thread.start();

如果我使用线程,它会打开表单并再次关闭它。

【问题讨论】:

  • 为什么要在另一个主题上打开一个表单?你的UI线程还不够吗?
  • 您不想创建多个 UI 线程。这会给你带来很多问题。你想要一个 UI 线程。
  • 是不是因为新表单打开时间长?
  • 你想通过添加另一个 UI 线程来实现什么?
  • @amc 解决方案是不在 UI 线程中执行非 UI 工作,而是在后台线程中执行,而不是在拥有 UI 时创建后台线程来执行 UI 工作线程做非 UI 工作。顾名思义,UI线程是做UI工作的,后台线程是做后台工作的。

标签: c# multithreading winforms visual-studio


【解决方案1】:

如果您只需将ApartmentState 设置为STA 并启动另一个消息循环,您可以创建另一个 UI 线程:

Thread _thread = new Thread(() =>
{
    Application.Run(new Form());
});
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();

请注意,您将无法在此表单的主线程上显示您创建的控件。这就是为什么创建多个 UI 线程通常是个坏主意。

【讨论】:

    【解决方案2】:
    Thread thd = new Thread(() =>
                {
    
                    //Do Some stuff 
                    //Do some more stuff
    
                    var dispatcher = Dispatcher.CurrentDispatcher;
                    dispatcher.UnhandledException += Dispatcher_UnhandledException; //you exception handling logic
                    Dispatcher.Run();
                });
                thd.IsBackground = true;
                thd.SetApartmentState(ApartmentState.STA);
                thd.Start();
    

    完成后根据您的用例调用Dispacther.InvokeShutdown();

    【讨论】:

      【解决方案3】:

      通过使用ShowDialog,它仅在窗口关闭时返回:

      new Thread(() => new MyForm().ShowDialog()).Start();
      

      【讨论】:

        猜你喜欢
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多