我将如何在工作线程中执行它? [英] How would i execute it in worker thread ?
问题描述
考虑下面的代码,我通过读取MS Access数据库将节点添加到树视图控件。
显然,如果我在一个单独的线程中执行,我会得到关于控件的异常从创建它的线程以外的线程访问。
现在每当我向树中添加一个节点时,我都可以将它解压缩到这样的GUI线程
您的代码未格式化且非常难以阅读。
更新c时从一个线程上对WinForm进行ontrols,使用Control.Invoke的派生来更新控件。
更新WinForm控件的一种非常安全的方法是使用BackgroundWorker生成线程组件。
这是一篇很好的文章讨论线程更新WinForms:
Windows窗体中的线程。
这是格式化的代码:
展开 | 选择 | Wrap | 行号
我会提出两点建议,但我没有写一个例子来证明它们能正常工作。如果他们不这样做,请告诉我。
建议#1:
- 在GUI中实例化初始TreeView。
- 将其作为参数传递到一个BackgroundWorker线程(也在GUI中创建)。
- 让线程填充节点(您发布的代码)。
- 处理RunWorkerCompleted事件以更新实际的显示已填写的TreeView。
- 如何使用:在后台运行操作。
建议#2:
如果在执行后仍然收到线程访问冲突如上所述,然后向GUI添加一个辅助方法,该方法将在线程中创建的节点克隆到GUI TreeView中的节点。这可以是一个简单的回归循环,并且应该快速运行,因为您已经在线程中执行了数据访问部分。
但是,我真的相信第二步不是必需的。如果从GUI生成BackgroundWorker线程,则保证在与GUI本身相同的线程上执行。它在Component命名空间中专门提供,以消除与WinForms相关的交叉线程问题。
Consider the following code in which i add nodes to a treeview control by reading an MS Access database.
Obviously, if I execute in a seperate thread I will get exception about control accessed from a thread other than the one in which it is created.
Now whenever I am adding one node to the tree I could marshel it to the GUI thread like this
Expand|Select|Wrap|Line Numbers解决方案Your code is unformatted and very difficult to read.
When updating controls on a WinForm from a thread, use a derivative of Control.Invoke to update the control.
A very safe way to update controls on a WinForm is to spawn the thread using a BackgroundWorker component.
Here is a great article discussing thread updating WinForms:
Threading in Windows Forms.
Here is the formatted code :
Expand|Select|Wrap|Line Numbers
I will make two suggestions, but I have not written an example to prove they will work correctly. Let me know if they do not.
Suggestion #1:
- Instantiate the initial TreeView in the GUI.
- Pass it as a parameter to a BackgroundWorker thread (also created in the GUI).
- Have the thread fill in the nodes (your posted code).
- Handle the RunWorkerCompleted event to update the actual display of the filled-in TreeView.
- How To: Run an Operation in the Background.
Suggestion #2:
If you still receive a thread access violation after implementing the above, then add a helper method to your GUI which will clone the nodes created in the thread to the nodes in your GUI TreeView. This can be a simple recusion loop and should run quickly, since you have already performed the data access part in your thread.
However, I truly believe the second step will not be necessary. If you spawn a BackgroundWorker thread from the GUI, it is guaranteed to execute on the same thread as the GUI itself. It is provided in the Component namespace specifically to eliminate the cross-threading issues associated with WinForms.
这篇关于我将如何在工作线程中执行它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文登录 关闭
扫码关注1秒登录发送“验证码”获取 | 15天全站免登陆