c# - 多个 UI 线程 - Winforms

标签 c# winforms multithreading user-interface

我想在我的应用程序中创建多个 UI 线程。我模拟了如下场景。我在 background thread

中点击按钮创建一个新窗口/表单
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var thread = new Thread(() =>
            {
                Form f = new Form();
                Application.Run(f);
            });

            // thread.IsBackground = true; -- Not required. See Solution below
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
    }  
}

请注意 - 我正在执行 IsBackground = true 因为当用户关闭主窗体时,子窗体/窗口也应该关闭。 是否有更简洁/优雅的方式来实现同样的目标?

EDIT - I want to create dedicated UI threads for each window. I will have 10 such windows displaying real-time data in parallel.

解决方案 - 这样可以吗? (根据下面的 msdnHans 评论) 已经设置了公寓状态(见上面的代码)

protected override void OnClosed(EventArgs e)
{
    Application.Exit();
}

最佳答案

乱用线程迟早会害了你。

来自 MSDN:

Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread

当然,您可以根据需要使用任意多的线程,但不要试图创建一种变通方法来使用不同的线程来更新 UI。请改用工作线程/后台线程中的 Invoke/InvokeRequired

使用扩展方法使其更清晰:Automating the InvokeRequired code pattern

关于c# - 多个 UI 线程 - Winforms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7568376/

相关文章:

c# - WinForms Livecharts 图表标题

c# - 如何防止表单关闭时控件中的事件触发

c# - 如何重命名 TreeView 中的节点?

multithreading - 工作线程没有消息循环(MFC,Windows)。我们可以使其接收消息吗?

c++ - OpenMP 只创建一个线程

multithreading - 如何为每个线程自动全局初始化/取消初始化某些内容?

c# - C# 中的 'out' 修饰符

c# - 通过特定属性将列表转换为逗号分隔字符串的最简单方法?

c# - Cosmos DB 中的向后分页

c# serialport 问题