I have a background worker which calls a function within a separate class. This process may be required to be canceled at any time via a button click from the front end. I have tried using CancelAsync() but this has no effect. The cofunds_downloadfiles is the function which i am calling. How do i go about canceling the process?
TIA.
Private Sub btnProcessdld_Click(sender As System.Object, e As System.EventArgs) Handles btnProcessdld.Click
Dim cfHelper As New CoFundsHelper
If btnProcessdld.Text = "Process" Then
btnProcessdld.Text = "Cancel"
If chkDailyFiles.Checked = False And chkWeeklyFiles.Checked = False Then
MessageBox.Show("Please select which files you want to download")
Else
lblProgress.Text = "Processing...if you are downloading weekly files this may take a few minutes"
uaWaitdld.AnimationEnabled = True
uaWaitdld.AnimationSpeed = 50
uaWaitdld.MarqueeAnimationStyle = MarqueeAnimationStyle.Continuous
uaWaitdld.MarqueeMarkerWidth = 60
_backGroundWorkerdld = New BackgroundWorker
_backGroundWorkerdld.WorkerSupportsCancellation = True
_backGroundWorkerdld.RunWorkerAsync()
End If
ElseIf btnProcessdld.Text = "Cancel" Then
btnProcessdld.Text = "Process"
_backGroundWorkerdld.CancelAsync()
uaWaitdld.AnimationEnabled = False
End If
Private Sub StartProcessdld(ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) Handles _backGroundWorkerdld.DoWork
Dim cfHelper As New CoFundsHelper
cfHelper.ConnString = PremiumConnectionString
Dim dateValue As String
Dim weekly As Boolean = False
Dim daily As Boolean = False
If dtePicker.Value IsNot Nothing Then
dateValue = Format(dtePicker.Value, "yyyyMMdd")
If chkWeeklyFiles.Checked = True Then
weekly = True
End If
If chkDailyFiles.Checked = True Then
daily = True
End If
cfHelper.Cofunds_DownloadFiles(dateValue, weekly, daily)
Else
Throw (New Exception("Date Field is empty"))
End If
End Sub
Basically you can do the following:
cancellationpendingpropertye.Cancelled = truethen check this in the RunWorkerCompleted and decide what you have to do.if you need to cancel it, simply make a
Stop()sub in your class that does exactly that – stops the procedure. Then, you simply need to invoke it likeyou may need to suspend the background worker until the call from your main thread has returned. You do this using semaphores:
Private chk As New Semaphore(1,1,"checking1")You put this as a global variable to both your main thread and the background worker.chk.WaitOne()AFTER the line that need to execute.a.ReleaseThe semaphore is only needed if you need to make sure you wait for a result. It kind of defeats the purpose of multithreading but you can perform other actions in the worker before waiting for the main thread (like starting another thread with something else etc).
Other than that invoking a stop method should be enough. Sorry that i haven’t had time to analyze your code but i hope i put you in the right direction.