我正在使用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
最佳答案
BackgroundWorker 的文档非常清楚:
<小时/>You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.
样本"How to: Download a File in the Background"显示了在主线程和后台工作程序之间共享对象的一种示例方式 - 通过安排将此类对象存储在类级别的变量中。
关于VB.NET WinForms - 如何从BackgroundWorker的线程访问主线程的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6937300/