VB.net 停止后台工作者

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18437290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:06:48  来源:igfitidea点击:

VB.net stopping a backgroundworker

vb.netbackgroundworker

提问by Marc Intes

I want to create a button that could stop my background worker and end all the process it is working on.

我想创建一个按钮,可以停止我的后台工作人员并结束它正在处理的所有进程。

Here is my sample backgroundworker code:

这是我的示例后台工作代码:

       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

            Try
                If BackgroundWorker1.IsBusy <> True Then
                    BackgroundWorker1.RunWorkerAsync()
                End If
            Catch ex As Exception
            End Try

        End Sub

        Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

            Dim counter As Integer = 1

            Do

            'updated code with stop function----------------
            BackgroundWorker1.WorkerSupportsCancellation = True
            If BackgroundWorker1.CancellationPending Then
                e.Cancel = True
                ProgressBar1.Value = 0
                Exit Do
            End If
            'updated code with stop function----------------

            ListBox1.Items.Add(counter)

            ProgressBar1.Value = ((counter - 1) / limit) * 100
            counter = counter + 1
            Loop While(counter <= 999999999999999999)

        End Sub

        Private Sub BackgroundWorker1_ProgressChanged(sender As System.Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
            Try
            Catch ex As Exception
            End Try
        End Sub

        Private Sub BackgroundWorker1_Completed(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
            Try
            Catch ex As Exception
            End Try
        End Sub

        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False    
        End Sub

        'updated code with stop function----------------
        Private Sub StopButton_Click(sender As Object, e As EventArgs) Handles StopButton.Click
              If BackgroundWorker1.IsBusy Then

                  If BackgroundWorker1.WorkerSupportsCancellation Then                
                     BackgroundWorker1.CancelAsync()
                  End If
              End If
        End Sub
        'updated code with stop function----------------

I want to reset the loop and return the Progress Bar to 0% when i stop the backgroundworker.

我想在停止后台工作时重置循环并将进度条返回到 0%。

Is this possible?

这可能吗?



The code above has been updated and it is now working fine.

上面的代码已经更新,现在可以正常工作了。

I have added this code inside my do loop:

我在 do 循环中添加了这段代码:

        BackgroundWorker1.WorkerSupportsCancellation = True
        If BackgroundWorker1.CancellationPending Then
            e.Cancel = True
            ProgressBar1.Value = 0
            Exit Do
        End If

I created a button that stops the worker:

我创建了一个停止工作人员的按钮:

    Private Sub StopButton_Click(sender As Object, e As EventArgs) Handles StopButton.Click
          If BackgroundWorker1.IsBusy Then

              If BackgroundWorker1.WorkerSupportsCancellation Then                
                 BackgroundWorker1.CancelAsync()
              End If
          End If
    End Sub

回答by Heslacher

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

Backgroundworker 类具有CancelAsync()您需要调用以取消 bgw 的执行的方法。

You need to set the Backgroundworker.WorkerSupportsCancellationproperty to true and inside the while loop you need to check the CancellationPendingproperty wether the value is truewhich indicates a call to the CancelAsync()method.

您需要将该Backgroundworker.WorkerSupportsCancellation属性设置为 true,并且在 while 循环中,您需要检查该CancellationPending属性的值是否true指示对该CancelAsync()方法的调用。

If CancellationPendingevaluates 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.

如果CancellationPending计算结果为 true,您将(您应该已经这样做)调用重载ReportProgress()( Docu) 方法之一将您的 ProgressBar 值设置为所需的值。

EDIT: You should set the Cancelproperty of the DoWorkEventArgsto true so you can check the Cancelledproperty of the RunWorkerCompletedEventArgsinside the RunworkerCompletedevent.

编辑:您应该将 的Cancel属性设置DoWorkEventArgs为 true,以便您可以检查事件内部的Cancelled属性。RunWorkerCompletedEventArgsRunworkerCompleted

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

您也不应该访问位于 UI 线程中的任何控件。您最好使用ProgressChanged( Docu) 事件。

See: BackgroundWorker Docu

请参阅:BackgroundWorker 文档

回答by 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