C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: You can change some properties of the BackgroundWorker by right clicking on it and selecting Properties.
Also: You can click on the lightning bolt and add event handlers to your C# code file.
And: At this point, a BackgroundWorker1_DoWork event handler is created. A Sleep method call can simulate some processor-intensive work.
Class that uses DoWork event handler: VB.NET
Public Class Form1
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork
' Do some time-consuming work on this thread.
System.Threading.Thread.Sleep(1000)
End Sub
End Class
So: Let's look at the complete program so far. The program starts the BackgroundWorker when the enclosing Form1 loads.
Class that uses Load and RunWorkerAsync: VB.NET
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Start up the BackgroundWorker1.
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork
' Do some time-consuming work on this thread.
System.Threading.Thread.Sleep(1000)
End Sub
End Class
Finally: RunWorkerCompleted is invoked after about one second, and we show the value on the screen (30).
Class that introduces ArgumentType, RunWorkerCompleted: VB.NET
Public Class Form1
Public Class ArgumentType
Public _a As Int32
Public _b As Int32
End Class
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Create the argument object.
Dim args As ArgumentType = New ArgumentType()
args._a = 5
args._b = 6
' Start up the BackgroundWorker1.
' ... Pass argument object to it.
BackgroundWorker1.RunWorkerAsync(args)
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork
' Do some time-consuming work on this thread.
System.Threading.Thread.Sleep(1000)
' Get argument.
Dim args As ArgumentType = e.Argument
' Return value based on the argument.
e.Result = args._a * args._b
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BackgroundWorker1.RunWorkerCompleted
' Called when the BackgroundWorker is completed.
MessageBox.Show(e.Result.ToString())
End Sub
End Class
Review: The BackgroundWorker is both effective and relatively easy to use once you understand its concept.