VB.NET WinForms - How to access objects of main thread from BackgroundWorker's thread?
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 ListVie开发者_开发百科w 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
The documentation for BackgroundWorker is quite clear:
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.
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
contains an Argument
property in which you can store any object, such as a user-defined class containing instructions for manipulating the UI.
精彩评论