VBNET取消后台工作者

时间:2018-02-25 10:58:05

标签: vb.net backgroundworker

我是编程新手并决定从VB.NET开始。我正在为自己编写一个简单的程序,列出字符串中的所有文件。除了BackgroundWorker之外,一切都很顺利,我希望包含取消功能以防我想要更改我的搜索条件我不必关闭我的应用程序然后重新开始。然而,尽管在互联网上寻找解决方案,但我遇到了问题。他们都不适合我的案子。这是我的代码的一部分。你也可以提出一个更好的方法我会很感激。

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    BackgroundWorker1.WorkerSupportsCancellation = True
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If BackgroundWorker1.IsBusy Then
        MsgBox("Already Running...")
    Else
        BackgroundWorker1.RunWorkerAsync()
    End If
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    If BackgroundWorker1.IsBusy Then
        BackgroundWorker1.CancelAsync()
    Else
        MsgBox("Already Terminated...")
    End If
End Sub

Public Sub Lister(ByVal Root As String)
    Try
        For Each file In My.Computer.FileSystem.GetFiles(Root, FileIO.SearchOption.SearchTopLevelOnly)
            setLabelTxt(file, label1)
        Next

        For Each folder In My.Computer.FileSystem.GetDirectories(Root)
            Lister(folder)
        Next
    Catch ex As UnauthorizedAccessException

    End Try
End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Do
        If BackgroundWorker1.CancellationPending Then
            e.Cancel = True
            Exit Do
        Else
            Lister("C:\")
            Exit Do
        End If
    Loop
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    If e.Cancelled = True Then
        MsgBox("Cancelled")
    Else
        MsgBox("Completed")
    End If
End Sub

Private Sub setLabelTxt(ByVal text As String, ByVal lbl As Label)
    If lbl.InvokeRequired Then
        lbl.Invoke(New setLabelTxtInvoker(AddressOf setLabelTxt), text, lbl)
    Else
        lbl.Text = text
    End If
End Sub

Private Delegate Sub setLabelTxtInvoker(ByVal text As String, ByVal lbl As Label)

0 个答案:

没有答案