Answered Pass data from BackgroundWorker to main thread?

littlebigman

Well-known member
Joined
Jan 5, 2010
Messages
75
Programming Experience
Beginner
Hello

In a Windows Form, I need to delegate a lengthy action to a BackgroundWorker so that the main application doesn't freeze.

However, the code in the BackgroundWorker must send data back to the main application. This code from MSDN doesn't include how to do this:

VB.NET:
Private Sub setTextBackgroundWorkerBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles setTextBackgroundWorkerBtn.Click
   Me.backgroundWorker1.RunWorkerAsync()
End Sub 

Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
Handles backgroundWorker1.RunWorkerCompleted
   Me.textBox1.Text = "This text was set safely by BackgroundWorker." 
End Sub

Is there a way for a BackgroundWorker object to send data back to the main app without using a global variable?

Thank you.
 
Last edited:
You can pass back final data with e.Result, or with userState parameter of ReportProgress method for progress information.
 
Thanks John, problem solved.

Here's the code:
VB.NET:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
	'Lengthy process here
	e.Result = "Blah"
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    Me.RichTextBox1.AppendText(e.Result)
End Sub
 
Back
Top