c# – 多个UI线程 – Winforms
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 多个UI线程 – Winforms,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1375字,纯文字阅读大概需要2分钟。
内容图文
![c# – 多个UI线程 – Winforms](/upload/InfoBanner/zyjiaocheng/826/fb45b3b1162b4a9383e06809e70e54ce.jpg)
我想在我的应用程序中创建多个UI线程.我已经模拟了如下方案.我正在后台线程中单击按钮创建一个新窗口/窗体
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.
解决方案 – 这样好吗? (根据msdn和Hans的评论如下)
设置了公寓状态(见上面的代码)
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全部内容,希望文章能够帮你解决c# – 多个UI线程 – Winforms所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。