VB中的Backgroundworker无法正常工作?

时间:2013-12-28 18:10:56

标签: vb.net

我正在编写一个应用程序来获取并复制文件夹(由用户在列表框中选择)到指定位置,它有一个应该运行整个时间的进度条,但似乎后台工作者没有抓住进程..它只是冻结UI直到副本完成..当我在副本之间输入消息时,消息有效,所以我知道它能够正常工作..我错过了什么..

Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles Btn_SaveApps.Click

    bw.WorkerSupportsCancellation = True
    bw.WorkerReportsProgress = True

    AddHandler bw.DoWork, AddressOf bw_DoWork
    AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
    AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
    If Not bw.IsBusy = True Then
        bw.RunWorkerAsync(Module1.SaveApp)
    End If

End Sub       

Module Module1
Function SaveApp() As Process

    Dim WinStrApps As String = ("C:\TransferFrom")
    Form1.tbProgress.Style = ProgressBarStyle.Marquee

    For Each Item In Form1.Selected_Apps.SelectedItems
        On Error Resume Next

        Form1.tbProgress.Visible = True

        Dim FileLoc = ("C:\TransferTo\")
        If System.IO.Directory.Exists(WinStrApps + Item) = True Then

            Directory.CreateDirectory(FileLoc + Item)
            My.Computer.FileSystem.CopyDirectory(WinStrApps + Item, FileLoc + Item)

        Else
            MsgBox(Item + " does not exist, or is a system App. Please choose another application")

        End If
    Next

    MsgBox("Completed saving the applications")

End Function

1 个答案:

答案 0 :(得分:0)

我想你可能已经调用了错误的线程,线程必须在sub bw_DoWork中开始

Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    Module1.SaveApp
end sub

并且传递回UI线程的任何更新都需要传递给

Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
    Form1.tbProgress.value = e.ProgressPercentage
End Sub

然而,由于例程是Form1的私有例程,您将无法从sub访问更新例程...您可能需要在模块中创建一个委托。