Reputation: 31
I have a stop problem in the backgroundworker, I use the following commands for backgroundworker:
update codes
Private Sub UnpackSystem_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles UnpackSystem.DoWork
Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
For i As Integer = 1 To 100
If worker.CancellationPending Then
e.Cancel = True
Exit For
End If
worker.ReportProgress(i, i & " iterations complete")
Threading.Thread.Sleep(250)
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("cmd.exe", "/c bin\Imgtool\simg2img.exe tmp/system.img tmp/system.img.ext4")
oStartInfo.WindowStyle = ProcessWindowStyle.Hidden
oStartInfo.CreateNoWindow = True
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
TextBox8.Invoke(Sub() TextBox8.AppendText(Environment.NewLine & sOutput))
Next i
End Sub
Private Sub UnpackSystem_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles UnpackSystem.ProgressChanged
Me.ProgressBar5.Value = e.ProgressPercentage
End Sub
Private Sub UnpackSystem_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles UnpackSystem.RunWorkerCompleted
If e.Cancelled = True Then
TextBox8.AppendText(Environment.NewLine & "Canceled!")
ElseIf e.Error IsNot Nothing Then
TextBox8.AppendText(Environment.NewLine & "Error: " & e.Error.Message)
Else
TextBox8.AppendText(Environment.NewLine & "Done!")
End If
End Sub
and, I use the following code to stop backgroundworker proccess ...
Private Sub Button55_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles Button55.Click
If Me.UnpackSystem.IsBusy Then
Me.UnpackSystem.CancelAsync()
End If
Dim cmd() As Process
cmd = Process.GetProcessesByName("cmd")
If cmd.Count > 0 Then
Process.GetProcessesByName("cmd")(0).Kill()
End If
End Sub
But it not be canceled, Where is my problem?
Upvotes: 0
Views: 599
Reputation: 54427
You are only testing whether a cancellation is pending when the DoWork
event handler first starts, which of course it will not be at that stage. In order for the background task to be cancelled later on, you would have to actually test whether a cancellation is pending later on.
There's no magic here though. As I said, in order to cancel, you have to actually test whether a cancellation is pending within the DoWork
event handler. That test can only come between other lines of code. Once you call that ReadToEnd
method, you are going to read the stream to the end, whether the user has requested cancellation or not. You obviously can't test for a pending cancelation until that call returns
Upvotes: 1