[RESOLVED] Pass data from BackgroundWorker to main thread?
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:
Code:
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.
Re: Pass data from BackgroundWorker to main thread?
For others' benefit, here's some working code:
Code:
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
Re: [RESOLVED] Pass data from BackgroundWorker to main thread?
If you need more than just the final result, or regular updates from the worker thread you could also use Delegate and Invoke..
Code:
Delegate Sub InvokeDelegText(ByVal value As String)
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'Lengthy process here
If Progress.LblProgress.InvokeRequired Then
' It's on a different thread, so use Invoke.
Progress.LblProgress.BeginInvoke(New InvokeDelegText(AddressOf SetText), text)
End If
'Lengthy process here
If Progress.LblProgress.InvokeRequired Then
' It's on a different thread, so use Invoke.
Progress.LblProgress.BeginInvoke(New InvokeDelegText(AddressOf SetText), text)
End If
End Sub
Private Sub SetText(ByVal Text As String)
Progress.LblProgress.Text = Text
End Sub
This code is very handy for passing any amount of data between threads.. I use it now extensively in many Multi threaded applications..