3

我想创建两个按钮来暂停和恢复我的后台工作人员,但我不知道从哪里开始我的代码,我刚刚开始学习 VB.net 并想了解后台工作人员的暂停和恢复功能。

这是我希望暂停和恢复的现有 BackgroundWorker 代码

Public resetevent As New ManualResetEvent(False)
Dim boo As Nullable(Of Boolean) = True

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Try
        If BackgroundWorker2.IsBusy <> True Then
            BackgroundWorker2.RunWorkerAsync()
            resetevent.Set()

        End If
    Catch ex As Exception

    End Try
End Sub

Private Sub BackgroundWorker2_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
    Dim worker2 As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)
    Try

        Dim Stream As New System.IO.FileStream("Sample.txt", IO.FileMode.Open)
        Dim sReader As New System.IO.StreamReader(Stream)
        Dim Index As Integer = 0


        Do While sReader.Peek >= 0
            resetevent.WaitOne()
            Thread.Sleep(500)
            eList.Add(sReader.ReadLine)
            Delay(1)
        Loop
        eArray = eList.ToArray
        Thread.Sleep(1000)

        Stream.Close()
        sReader.close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

Private Sub BackgroundWorker2_ProgressChanged(sender As System.Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker2.ProgressChanged
    Try

    Catch ex As Exception

    End Try
End Sub

Private Sub BackgroundWorker2_Completed(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker2.RunWorkerCompleted
    Try
       resetevent.Reset()
    Catch ex As Exception

    End Try
End Sub

Private Sub pause_Click(sender As Object, e As EventArgs) Handles pause.Click
    pause.Enabled = False
    resme.Enabled = True

    If BackgroundWorker1.IsBusy Then
        boo = False
        resetevent.Reset()
    End If



End Sub

Private Sub resme_Click(sender As Object, e As EventArgs) Handles resme.Click
    resme.Enabled = False
    pause.Enabled = True

    If BackgroundWorker1.IsBusy Then
        boo = True
        resetevent.Set()
    End If

此代码现在可以使用,感谢您的提示

4

1 回答 1

3

请看一下

后台工作人员中的暂停/恢复循环

如何暂停和恢复 BackgroundWorker?

如何使用 BackgroundWorker c# 实现暂停和恢复功能

使用转换器来转换您需要转换的代码。这些都应该为您提供答案。

于 2013-07-25T17:36:10.763 回答