C# 我可以使用后台线程向列表框添加值吗?
我希望我的后台工作人员将项目添加到列表框中,在调试时似乎是这样做的,但列表框不显示值。 我怀疑这与在后台工作线程内添加项目有关,我是否需要将这些项目添加到数组中,然后在 backgroundWorker1_RunWorkerCompleted
期间从数组填充列表框?
谢谢您的帮助。
I want my background worker to add items to a list box, it appears to do so when debugging but the listbox doesn't show the values. I suspect this is something to do with adding items whilst inside the background worker thread, do I need to add these to an array and then populate the list box from the array during backgroundWorker1_RunWorkerCompleted
?
Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以像这样使用 Invoke:
You can use Invoke like this:
您可以,但您必须建议您的后台工作人员报告状态,并将具有当前状态的框的输入发送到该事件。 在该事件的方法中,您可以访问该框并放入新值。
否则您需要手动调用。
You can, but you must advise your Backgroundworker to report state, and send the input for the box with the current state to that event. In the method for that event, you can access the box and put the new value in.
Otherwise you need to invoke manually.
我添加了如下所示的函数,以便可以从主线程或后台线程将项目添加到列表框中。 该线程检查是否需要 Invoke,然后在需要时使用 Invoke。
I add functions like the following so that I can add items to the list box from either the main thread or background threads. Thi thread checks if a Invoke is necessary and then uses Invoke if it is necessary.
您可以通过以下方式在后台线程上添加它们:
或
将调用从后台线程编组到主 UI 线程所需的。
不过我很确定BackgroundWorker 提供了一个在Foreground 线程上自动调用的事件,并且您应该能够毫无问题地更新此事件。
这是“ProgressChanged”,可以由后台工作进程通过调用 ReportProgress 来触发。
您是否也尝试过在列表框中调用
.Refresh()
?You can add them while on a background thread via:
or
which are required to marshall the call from a background thread to a main UI thread.
However I'm pretty sure BackgroundWorker offers an event that automatically gets called on the Foreground thread and you should be able to update on this event without any problems.
This is "ProgressChanged" which can be fired by the background worker process by calling ReportProgress.
Have you tried calling
.Refresh()
on the listbox as well?如果您正在尝试更新数据库。 我建议从列表框中创建一个数据集。
例如,如果您对数据库中的每个项目执行某些操作。 通过创建新数据集并通过 mainDataset 声明来复制数据库数据集。
例如:
// gridview数据集是dataset1
if you are trying to update a database. From a listbox i would suggest creating a dataset.
for instance, if your doing something for each item in a database. Copy the database dataset, by creating new dataset and declaring by mainDataset.
for example:
// the gridview dataset is dataset1
Application.Doevents()
函数将解决该问题。Application.Doevents()
function will solve the problem.