The background worker allows you to execute intense or long operations on a separate thread, without having to deal with threads, invokes or delegates. This has become somewhat essential in today's intense applications.
Hmm, lets make an application that can demonstrate the working of BackGroundWorker !!!
Drag a backgroundworker instance to the stage using Toolbox. Name it Bg_Worker.
Also enable 'WorkerReportsProgress' from the properties box.
Drag a progress bar, name it pb.
Drag two buttons. Set the text of the first button to "Start" and set the second to "Stop".
Drag a richtextbox1 and name it "txtOutput".
Now add the following code to your main form.
[php] Private Sub BG_Worker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BG_Worker.DoWork
Dim start As DateTime = DateTime.Now
e.Result = ""
For i As Integer = 0 To 99
System.Threading.Thread.Sleep(50)
'do some intense task here.
BG_Worker.ReportProgress(i, DateTime.Now)
'notify progress to main thread. We also pass time information in UserState to cover this property in the example.
'Error handling: uncomment this code if you want to test how an exception is handled by the background worker.
'also uncomment the mentioned attribute above to it doesn't stop in the debugger.
'if (i == 34)
' throw new Exception("something wrong here!!");
'if cancellation is pending, cancel work.
If BG_Worker.CancellationPending Then
e.Cancel = True
Exit Sub
End If
Next
Dim duration As TimeSpan = DateTime.Now - start
'we could return some useful information here, like calculation output, number of items affected, etc.. to the main thread.
'}
'catch(Exception ex){
' MessageBox.Show("Don't use try catch here, let the backgroundworker handle it for you!");
'}
e.Result = "Duration: " & duration.TotalMilliseconds.ToString() & " ms."
End Sub
Private Sub BG_Worker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BG_Worker.ProgressChanged
pb.Value = e.ProgressPercentage
'update progress bar
Dim time As DateTime = Convert.ToDateTime(e.UserState)
'get additional information about progress
'in this example, we log that optional additional info to textbox
txtOutput.AppendText(time.ToLongTimeString())
txtOutput.AppendText(Environment.NewLine)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub BG_Worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BG_Worker.RunWorkerCompleted
If e.Cancelled Then
MessageBox.Show("The task has been cancelled")
ElseIf e.[Error] IsNot Nothing Then
MessageBox.Show("Error. Details: " & TryCast(e.[Error], Exception).ToString())
Else
MessageBox.Show("The task has been completed. Results: " & e.Result.ToString())
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BG_Worker.RunWorkerAsync()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
BG_Worker.CancelAsync()
End Sub[/php]
Basically, the background worker performs an intense operation. If you don't use it in this case (Update Date in the richtextbox), the application will hang. So it creates a seperate thread and performs the intense operation there....
Background worker simultaneously, reports the progress, which is displayed in the progress bar !! I hope you can understand the code. Its pretty easy !!!!
This code is my conversion from this page: Backgroundworker example
I hope you find it useful, and u have understand what it does.