单独线程上的C#UI [英] C# UI on separate thread

查看:109
本文介绍了单独线程上的C#UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断在各种论坛,教程或SO上看到一个建议,建议在单独的线程上运行UI,然后在程序的其余部分保持UI的响应速度.
在实践中这是如何完成的?这是否意味着在加载表单之前编辑program.cs以启动线程?还是意味着从表单内部激活的任何非平凡操作都会派生线程并使用该线程?还是有一些设置?您如何使用它?

I keep seeing on various forums, tutorials or SO answers a recommendation to run the UI on a separate thread then the rest of the program to keep it responsive.
How is this done in practice? Does it mean editing program.cs to start a thread before loading the form? Or does it mean that any non-trivial operation activated from within the form fork a thread and use that? Or is it some setting? How do you work with it??

推荐答案

要使UI保持响应状态,您应该在单独的线程中运行 other 耗时的操作.通常,用户界面操作应在.NET的主(UI)线程中完成.

To keep UI responsive you should run other time consuming operations in a separate thread. Usually user interface operations should be done in .NET's main (UI) thread.

有几种方法可以使用单独的(后台)线程进行操作.对于Windows窗体应用程序,最简单的选项是 BackgroundWorker 组件.

There are several ways to use a separate (background) thread for your operations. For Windows Forms applications, simplest option is BackgroundWorker component.

您还可以创建 Thread 反对自己.但是,在调用UI方法或更改创建的线程中的UI控件属性时,应格外小心.正如我所说,所有用户界面操作(显示表单,更改控件文本或位置等)都应该在UI线程中完成.否则,您将获得例外.为此,您可以使用 Control.Invoke 方法.

You can also create a Thread object yourself. But you should be careful about calling UI methods or changing UI controls properties in created thread. As I said, all the user interface operations (showing forms, changing controls texts or locations and so on) should be done in UI thread. Otherwise you get an exception. To do that, you can use Control.Invoke method.

这篇关于单独线程上的C#UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆