vb.net backgroundworker CancelAsync不起作用

时间:2017-11-06 07:18:07

标签: vb.net

我在backgroundworker中遇到了问题,我使用以下命令进行后台工作:

更新代码

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

并且,我使用以下代码来停止后台工作程序...

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

但它没有被取消,我的问题在哪里?

1 个答案:

答案 0 :(得分:1)

您只是在DoWork事件处理程序首次启动时测试取消是否处于暂挂状态,当然它不会处于该阶段。为了稍后取消后台任务,您必须在以后实际测试取消是否待处理。

虽然这里没有魔法。正如我所说,为了取消,您必须在DoWork事件处理程序中实际测试取消是否未决。该测试只能在其他代码行之间进行。一旦调用ReadToEnd方法,您将读到最后的流,无论用户是否请求取消。在调用返回

之前,您显然无法测试待处理的取消