VB.NET WinForms - 如何从BackgroundWorker的线程访问主线程的对象?
我正在使用 BackgroundWorker
,我希望 BackgroundWorker
执行从数据库中检索数据的过程,同时用户仍然可以在表单上执行其他任务。问题是,检索数据后,我似乎无法从 BackgroundWorker
的 DoWork
事件访问我的 Form
中的 ListView,我将使用我检索到的数据填充该 ListView。我应该怎么办?我错过了什么吗?
考虑这个例子,我就是这样做的:
Public Class Test
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Label1.Text = "Hello World"
End Sub
End Class
I'm working with BackgroundWorker
, I want the BackgroundWorker
do the retrieval process of data from database while the user can still do another task on the form. The problem is, after retrieving the data, I can't seem to access the ListView in my Form
from the DoWork
event of BackgroundWorker
, I will populate that ListView using the data I've retrieved. What should I do? Am I missing something?
Consider this example, this is how I'm doing it:
Public Class Test
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Label1.Text = "Hello World"
End Sub
End Class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BackgroundWorker 的文档非常清楚:
示例“如何:在后台下载文件” 显示了一个可以在主线程和后台工作人员之间共享对象的示例方式 - 通过安排将此类对象存储在类级别的变量中。
The documentation for BackgroundWorker is quite clear:
The sample "How to: Download a File in the Background" shows one example way that objects can be shared between the main thread and the background worker - by arranging for such objects to be stored in variables at the class level.
DoWorkEventArgs
包含一个Argument
属性,您可以在其中存储任何对象,例如包含用于操作 UI 的指令的用户定义的类。DoWorkEventArgs
contains anArgument
property in which you can store any object, such as a user-defined class containing instructions for manipulating the UI.