多个 UI 线程 - Winforms [英] Multiple UI Threads - Winforms
问题描述
我想在我的应用程序中创建多个 UI 线程.我已经模拟了如下场景.我正在背景线程
I want to create multiple UI threads in my application. I have simulated the scenario as below. I am creating a new window / form on a button click in a 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 ,因为当用户关闭主窗体时,子窗体/窗口也应该关闭.是否有更干净/更优雅的方式来实现相同的目标?
Note that - I am doing IsBackground = true bacause when the user closes on the main form, the child forms/windows should also close down. Is there a more cleaner/graceful way to achieve the same ?
编辑 - 我想为每个窗口创建专用的 UI 线程.我将会有10个这样的窗口并行显示实时数据.
EDIT - I want to create dedicated UI threads for each window. I will have 10 such windows displaying real-time data in parallel.
解决方案 - 可以吗?(根据 msdn 和 Hans' 评论如下)已经设置了公寓状态(见上面的代码)
Solution - Is this fine ? (as per msdn and Hans' comments below) have set the Apartment state (see code above)
protected override void OnClosed(EventArgs e)
{
Application.Exit();
}
推荐答案
乱七八糟的话题迟早会害了你.
Messing with threads will only bite you sooner or later.
来自 MSDN:
Windows 窗体中的控件绑定到特定线程并且不是线程安全的.因此,如果您从不同的线程调用控件的方法,则必须使用控件的调用方法之一将调用编组到正确的线程
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
.
You can of course use as many threads as you like, but don't try to create a workaround to be able to use different threads for updating the UI. Use Invoke
/InvokeRequired
from your worker/background threads instead.
使用扩展方法使其更简洁:自动化 InvokeRequired 代码模式
Using an extension method makes it cleaner: Automating the InvokeRequired code pattern
这篇关于多个 UI 线程 - Winforms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!