Is there a way to do this without having as much code? ie, a "proper" way of doing this?
No guarantees if this will do what you want it to. :)
- ''' <summary>Allows tieing events to a worker without additional code</summary>
-
Public Class BackgroundWorkerCreation
-
Private _worker As BackgroundWorker
-
-
''' <summary>Initialize the worker and tie on events</summary>
-
''' <param name="subDoWork">New DoWorkEventHandler(AddressOf onDoWork)</param>
-
''' <param name="subProgressChanged">New ProgressChangedEventHandler(AddressOf onProgressChanged)</param>
-
''' <param name="subWorkerCompleted">New RunWorkerCompletedEventHandler(AddressOf onWorkerCompleted)</param>
-
''' <param name="SupportCancelation"></param>
-
''' <param name="StartWorkerNow">"False" to start the worker at a later time</param>
-
Public Sub CreateWorker(ByVal subDoWork As DoWorkEventHandler, Optional ByVal subProgressChanged As ProgressChangedEventHandler = Nothing, _
-
Optional ByVal subWorkerCompleted As RunWorkerCompletedEventHandler = Nothing, _
-
Optional ByVal SupportCancelation As Boolean = False, _
-
Optional ByVal StartWorkerNow As Boolean = True)
-
-
'* To use the background worker, you'll need to type in the arguments similar to what is shown:
-
-
'New DoWorkEventHandler(AddressOf subDoWork)
-
'New ProgressChangedEventHandler(AddressOf onProgressChanged)
-
'New RunWorkerCompletedEventHandler(AddressOf onWorkerCompleted)
-
-
' Instantiate the worker
-
Dim worker As New BackgroundWorker
-
-
' Tie in the DoWork event
-
AddHandler worker.DoWork, subDoWork ' Create delegate handle
-
-
' Tie in the ReportsProgress event
-
If subProgressChanged Is Nothing Then
-
worker.WorkerReportsProgress = False
-
Else
-
worker.WorkerReportsProgress = True
-
AddHandler worker.ProgressChanged, subProgressChanged ' Create callback handle
-
End If
-
-
' Tie in the RunWorkerCompleted event
-
If subProgressChanged IsNot Nothing Then AddHandler worker.RunWorkerCompleted, subWorkerCompleted ' Create completion handle
-
-
' Allow Cancelation
-
worker.WorkerSupportsCancellation = SupportCancelation
-
-
'* Start the worker
-
If StartWorkerNow = True Then StartWorker()
-
End Sub
-
-
''' <summary>Start or Re-start the background worker. If the worker is still running, this sub will do nothing.</summary>
-
Public Sub StartWorker()
-
If _worker.IsBusy = False Then _worker.RunWorkerAsync()
-
End Sub
-
-
''' <summary>Notify the worker that it should cancel. Will only work if the worker supports cancellation.</summary>
-
Public Sub CancelWorker()
-
If _worker.WorkerSupportsCancellation = True And _worker.IsBusy Then _worker.CancelAsync()
-
End Sub
-
-
''' <summary>Releases all resources used by the System.ComponentModel.Component</summary>
-
Public Sub Dispose()
-
_worker.Dispose()
-
End Sub
-
End Class