C# 如何实现一个与控件一起使用并启用线程的类?
我已经编写了一个为我填充树视图的类。在我的项目中,我多次需要这个树视图,但我不想复制粘贴我的代码,所以我决定创建一个类来填充树视图。
在某些表单上,我想使用线程来填充树视图。这是因为有时加载数据并填充树视图可能需要一些时间。
在我的树视图类中,我在构造函数中传递了树视图。现在我想要填充树视图,我调用 LoadTreeview()
方法。
我想在线程上调用 LoadTreeview 方法,但是当我这样做时,我得到了一个异常,即树视图是在另一个线程上创建的。这当然是不符合逻辑的。但我想知道,创建与控件一起使用的自定义类的最佳方法是什么,并且您想在线程中使用此类?
我需要在每个“GUI 操作”上编写此代码吗?
treeview.Invoke((MethodInvoker)delegate
{
treeview.Nodes.Add(MyNode);
})
或者还有其他(更聪明的)方法吗?
I have written a class that fills a treeview for me. IN my project I need this treeview several times and I don;t want to copy paste my code, so I decided to create a class that fills the treeview for me.
On some forms I want to use a thread to fill the treeview. This is because sometimes it can take some time to load the data and fill the treeview.
In my treeview-class I pass the treeview in the constructor. At the moment I want to fill the treeview, I call the LoadTreeview()
method.
I'd like to call the LoadTreeview
method on a thread, but when I do this I get the exception that the treeview is created on another thread. Which is logic off course. But I was wondering, what is the best way to create a custom class that works with controls and you want to use this class in a thread?
Do I need to write this code on every 'GUI-action'?
treeview.Invoke((MethodInvoker)delegate
{
treeview.Nodes.Add(MyNode);
})
Or are there other (smarter) ways?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您和 Levisaxos 的解决方案都可以防止崩溃,但您应该真正对其运行时性能进行基准测试。问题是,如果您向树视图插入大量节点,并且每个节点都是通过 Control.Invoke 插入的,您的代码将不会做太多事情,只会同步到 UI 线程。如果是这种情况,您应该考虑将创建树视图节点所需的数据与实际插入节点分开加载。相反,异步加载数据,然后一次同步插入所有节点。
Both your and Levisaxos' solutions will prevent the crash but you should really benchmark the runtime performance of this. The problem is that if you insert lots of nodes to the treeview and each node is inserted through Control.Invoke your code will not be doing much but synchronizing to the UI thread. If this is the case you should consider to separate loading the data that is needed to create the nodes for the treeview from the actual insertion of the nodes. Instead load the data asynchronously and then synchronously insert all nodes at once.
我希望这对你有帮助。这就是我处理异步操作的方式。
[编辑]
取决于您想如何使用它。
在一个线程中:
据我所知,这会起作用。
I hope this helps you. This is how I am handeling Async operations.
[edit]
Depending on how you want to use it.
In a thread:
As far as I know this will work.