VB.net stopping a backgroundworker

筅森魡賤 提交于 2019-12-03 16:03:41

The Backgroundworker class has the method CancelAsync() which you need to call to cancel the execution of the bgw.

You need to set the Backgroundworker.WorkerSupportsCancellation property to true and inside the while loop you need to check the CancellationPending property wether the value is true which indicates a call to the CancelAsync() method.

If CancellationPending evaluates to true, you would ( which you should have done already ) call one of the overloaded ReportProgress() (Docu) methods to set your ProgressBar value to the desired value.

EDIT: You should set the Cancel property of the DoWorkEventArgs to true so you can check the Cancelled property of the RunWorkerCompletedEventArgs inside the RunworkerCompletedevent.

You also shouldn not access any controls which lives in the UI thread. You better use the ProgressChanged(Docu) event.

See: BackgroundWorker Docu

Thaanuja
Public Class Form1
    Private iVal As Integer = 0
    Private Sub bgw_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        For iVal = iVal To 100 Step 1
            bgw.ReportProgress(iVal)
            Threading.Thread.Sleep(99)
            If (bgw.CancellationPending = True) Then
                e.Cancel = True
                Exit For
            End If
        Next
    End Sub

    Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
        pbar.Value = e.ProgressPercentage
        lblProgrss.Text = e.ProgressPercentage.ToString() & "%"
    End Sub

    Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted

        If (e.Cancelled = True) Then
            pic.Visible = False
            pbar.Value = iVal
            lblProgrss.Text = iVal & "%"
            btnstart.Text = "Start"
            btnstart.BackColor = Color.Green
        Else
            pic.Visible = False
            btnstart.Text = "Start"
            btnstart.BackColor = Color.Green
            iVal = 0
        End If

    End Sub

    Private Sub btnstart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnstart.Click
        If (btnstart.Text = "Start") Then
            btnstart.Text = "Stop"
            btnstart.BackColor = Color.Red
            pic.Visible = True
            bgw.RunWorkerAsync()
        Else
            If (bgw.IsBusy = True) Then
                btnstart.Text = "Start"
                btnstart.BackColor = Color.Green
                bgw.CancelAsync()
            End If
        End If
    End Sub
End Class
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!