Vb.net 用于从';复制文件的进度条;我的资源';图书管理系统

Vb.net 用于从';复制文件的进度条;我的资源';图书管理系统,vb.net,progress-bar,file-copying,my.resources,Vb.net,Progress Bar,File Copying,My.resources,我试图用进度条从“My.resources”复制文件,我搜索了许多其他文件复制进度条脚本,但没有一个支持从内部复制;文件夹。这是我的密码: Private Sub Install_Click(sender As Object, e As System.EventArgs) Handles Install.Click InstallDialog.ShowNewFolderButton = True InstallDialog.ShowDialog() If Not (IO.

我试图用进度条从“My.resources”复制文件,我搜索了许多其他文件复制进度条脚本,但没有一个支持从内部复制;文件夹。这是我的密码:

Private Sub Install_Click(sender As Object, e As System.EventArgs) Handles Install.Click
    InstallDialog.ShowNewFolderButton = True
    InstallDialog.ShowDialog()
    If Not (IO.Directory.Exists(IO.Path.GetTempPath & "extract")) Then
        IO.Directory.CreateDirectory(IO.Path.GetTempPath & "extract")
    End If
    If Not (InstallDialog.SelectedPath = "") Then
        Dim exepath As String = IO.Path.GetTempPath & "extract\7zG.exe"
        Dim archpath As String = IO.Path.GetTempPath & "extract\arch.7z"
        If File.Exists(archpath) = False Then
            Dim b As Byte() = My.Resources.arch
            Dim TempFile As IO.FileStream = IO.File.Create(archpath)
            TempFile.Write(b, 0, b.Length)'Copies the archive to disk
            TempFile.Flush()
            TempFile.Close()
        End If
        If File.Exists(exepath) = False Then
            Dim c As Byte() = My.Resources.zipexe
            Dim TempFile As IO.FileStream = IO.File.Create(exepath)
            TempFile.Write(c, 0, c.Length)'Copies the 7-zip executable to disk
            TempFile.Flush()
            TempFile.Close()
        End If
            Dim p As New ProcessStartInfo
            p.WindowStyle = ProcessWindowStyle.Normal
            p.FileName = exepath
            p.Arguments = " x " & archpath & " -mmt -aoa -o" & InstallDialog.SelectedPath
            Dim Extract As Process = Process.Start(p)'runs 7-zip to extract the archive
            Dim i As Boolean = True
            Do While i = True
                If Extract.HasExited = True Then
                    i = False
                Else
                    Threading.Thread.Sleep(2000)
                End If
            Loop
            Msgbox("Installation Complete")            
    End If
End Sub
我的进度条名为“copyprog”,
“arch.7z”大约有150Mb,在复制时UI会挂起,我的用户使用的是速度非常慢的机器,他们希望得到一些响应,而不是在点击按钮时应用程序冻结。

如果您可以使用VS2012和/或异步功能,它或多或少都很简单。请注意,与往常一样,对于给定的问题,有几十个“有效”的解决方案

    ' Write a file with progressbar updates

    Dim output(1000 * 1000) As Byte ' the bytes to be written
    Dim numbytes As Integer = 4096 ' number of bytes per write command

    Using fs As New FileStream("path", FileMode.Create, FileAccess.Write, FileShare.Read)
        Dim outpointer As Integer = 0
        While outpointer <> output.Length
            numbytes = Math.Min(numbytes, output.Length - outpointer)
            Await fs.WriteAsync(output, outpointer, numbytes)
            outpointer += numbytes
            ProgressBar1.Value = (outpointer * 100) \ output.Length
        End While
        Await fs.FlushAsync
    End Using

    ' Wait for a process to be done
    Dim p As New Process With {.EnableRaisingEvents = True, .StartInfo = New ProcessStartInfo("notepad.exe")}
    Dim cts As New CancellationTokenSource
    Dim exithandler = Sub(prc As Object, ev As EventArgs)
                          cts.Cancel()
                      End Sub
    AddHandler p.Exited, exithandler

    ProgressBar1.Style = ProgressBarStyle.Marquee
    p.Start()

    Try
        Dim t = Task.Delay(TimeSpan.FromSeconds(5), cts.Token)
        Await t
        If t.Status = TaskStatus.RanToCompletion Then
            MessageBox.Show("Process still executing! Might be an error! What can we do?")
        End If
    Catch ex As TaskCanceledException
        ' thats ok! we WANT the task to be cancelled!
    End Try

    ProgressBar1.Style = ProgressBarStyle.Continuous
    ProgressBar1.Value = ProgressBar1.Minimum

    MessageBox.Show("all done!")
'编写带有progressbar更新的文件
Dim输出(1000*1000)为字节“待写入的字节
Dim numbytes As Integer=4096'每个写入命令的字节数
将fs用作新的文件流(“路径”,FileMode.Create,FileAccess.Write,FileShare.Read)
作为整数的Dim输出指针=0
而输出指针输出。长度
numbytes=Math.Min(numbytes,output.Length-outpointer)
等待fs.WriteAsync(输出、输出指针、数字节)
输出指针+=字节数
ProgressBar1.Value=(输出指针*100)\output.Length
结束时
等待fs.FlushAsync
终端使用
'等待流程完成
使用{.EnableRaisingEvents=True、.StartInfo=New ProcessStartInfo(“notepad.exe”)}将p作为新进程进行调整
Dim cts作为新的CancellationTokenSource
Dim exithandler=Sub(prc作为对象,ev作为事件参数)
cts.Cancel()
端接头
AddHandler p.已退出,exithandler
ProgressBar1.Style=ProgressBarStyle.Marquee
p、 开始()
尝试
Dim t=任务延迟(时间跨度从秒(5),cts.Token)
等待
如果t.Status=TaskStatus.RanToCompletion,则
Show(“进程仍在执行!可能是错误!我们能做什么?”)
如果结束
捕获ex作为TaskCanceledException
“没关系!我们希望任务被取消!
结束尝试
ProgressBar1.Style=ProgressBarStyle.Continuous
ProgressBar1.值=ProgressBar1.最小值
MessageBox.Show(“全部完成!”)

其主要优点是:它是在一个子系统中实现的,并且流程或多或少是线性的。如果你使用像sevenzipsharp(或任何其他合适的)这样的库,你甚至可以得到关于解压缩的进度反馈(我想)。如果您想继续使用外部exe,您可以尝试检查循环中的文件长度,以提供有关解压缩的反馈。

如果您可以使用VS2012和/或异步功能,它或多或少都很简单。请注意,与往常一样,对于给定的问题,有几十个“有效”的解决方案

    ' Write a file with progressbar updates

    Dim output(1000 * 1000) As Byte ' the bytes to be written
    Dim numbytes As Integer = 4096 ' number of bytes per write command

    Using fs As New FileStream("path", FileMode.Create, FileAccess.Write, FileShare.Read)
        Dim outpointer As Integer = 0
        While outpointer <> output.Length
            numbytes = Math.Min(numbytes, output.Length - outpointer)
            Await fs.WriteAsync(output, outpointer, numbytes)
            outpointer += numbytes
            ProgressBar1.Value = (outpointer * 100) \ output.Length
        End While
        Await fs.FlushAsync
    End Using

    ' Wait for a process to be done
    Dim p As New Process With {.EnableRaisingEvents = True, .StartInfo = New ProcessStartInfo("notepad.exe")}
    Dim cts As New CancellationTokenSource
    Dim exithandler = Sub(prc As Object, ev As EventArgs)
                          cts.Cancel()
                      End Sub
    AddHandler p.Exited, exithandler

    ProgressBar1.Style = ProgressBarStyle.Marquee
    p.Start()

    Try
        Dim t = Task.Delay(TimeSpan.FromSeconds(5), cts.Token)
        Await t
        If t.Status = TaskStatus.RanToCompletion Then
            MessageBox.Show("Process still executing! Might be an error! What can we do?")
        End If
    Catch ex As TaskCanceledException
        ' thats ok! we WANT the task to be cancelled!
    End Try

    ProgressBar1.Style = ProgressBarStyle.Continuous
    ProgressBar1.Value = ProgressBar1.Minimum

    MessageBox.Show("all done!")
'编写带有progressbar更新的文件
Dim输出(1000*1000)为字节“待写入的字节
Dim numbytes As Integer=4096'每个写入命令的字节数
将fs用作新的文件流(“路径”,FileMode.Create,FileAccess.Write,FileShare.Read)
作为整数的Dim输出指针=0
而输出指针输出。长度
numbytes=Math.Min(numbytes,output.Length-outpointer)
等待fs.WriteAsync(输出、输出指针、数字节)
输出指针+=字节数
ProgressBar1.Value=(输出指针*100)\output.Length
结束时
等待fs.FlushAsync
终端使用
'等待流程完成
使用{.EnableRaisingEvents=True、.StartInfo=New ProcessStartInfo(“notepad.exe”)}将p作为新进程进行调整
Dim cts作为新的CancellationTokenSource
Dim exithandler=Sub(prc作为对象,ev作为事件参数)
cts.Cancel()
端接头
AddHandler p.已退出,exithandler
ProgressBar1.Style=ProgressBarStyle.Marquee
p、 开始()
尝试
Dim t=任务延迟(时间跨度从秒(5),cts.Token)
等待
如果t.Status=TaskStatus.RanToCompletion,则
Show(“进程仍在执行!可能是错误!我们能做什么?”)
如果结束
捕获ex作为TaskCanceledException
“没关系!我们希望任务被取消!
结束尝试
ProgressBar1.Style=ProgressBarStyle.Continuous
ProgressBar1.值=ProgressBar1.最小值
MessageBox.Show(“全部完成!”)
其主要优点是:它是在一个子系统中实现的,并且流程或多或少是线性的。如果你使用像sevenzipsharp(或任何其他合适的)这样的库,你甚至可以得到关于解压缩的进度反馈(我想)。如果您想继续使用外部exe,您可以尝试检查循环中的文件长度,以提供有关解压缩的反馈。

这是实现所需功能的一种(多种)方法。这种方法使UI处于独立状态,因此可以很好地进行更新。我编写了对两个进度条的支持,一个用于总进度(文件数),一个用于当前进度。代码支持取消

根据需要使用和修改,它是按原样提供的

代码假设如前所述,表单上有两个进度条以及两个按钮(安装和取消)-请参阅下面的快照

用法 您只需将要复制的所有资源添加到任务列表中,然后启动提示

AddCopyTask(resourceToCopy1, pathToWhereToCopy1)
AddCopyTask(resourceToCopy2, pathToWhereToCopy2)
...
StartCopyCue()
完整代码:

Imports System.ComponentModel
Imports System.IO

Public Class Form1

    'If you use small file sizes, lower this value to have progress-bar going
    Private Const BufferSize As Integer = 4096

    Private WithEvents bgCopier As New BackgroundWorker

    Private Class WorkerPacket
        Public DataRef As Byte()
        Public Filename As String
    End Class

    Private taskList As New List(Of WorkerPacket)
    Private _cancel As Boolean = False

    '
    '-- Setup worker
    '
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        bgCopier.WorkerReportsProgress = True
        bgCopier.WorkerSupportsCancellation = True

    End Sub
    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        If bgCopier IsNot Nothing Then
            bgCopier.Dispose()
        End If

    End Sub
    '
    '-- UI
    '
    Private Sub Install_Click(sender As System.Object, e As System.EventArgs) Handles Install.Click

        '
        '-- This is where you initilize the paths and data you want to copy.
        '-- For this example I use the same data
        '
        AddCopyTask(My.Resources.TestData, "c:\test1.dat")
        AddCopyTask(My.Resources.TestData, "c:\test2.dat")
        AddCopyTask(My.Resources.TestData, "c:\test3.dat")

        StartCopyCue()

    End Sub
    Private Sub CancelCopy_Click(sender As System.Object, e As System.EventArgs) Handles CancelCopy.Click

        _cancel = True

        If bgCopier.IsBusy Then
            bgCopier.CancelAsync()
        End If

    End Sub
    '
    '-- The methods to build and perform task-list
    '
    Private Sub AddCopyTask(data As Byte(), filename As String)
        '
        '-- Create argument packet for worker
        '
        Dim wp As New WorkerPacket
        wp.DataRef = data
        wp.Filename = filename

        taskList.Add(wp)

    End Sub
    Private Sub StartCopyCue()
        '
        '-- Init total progressbar
        '
        ProgressBarTotal.Value = 0
        ProgressBarTotal.Maximum = taskList.Count

        _cancel = False
        '
        '-- Update UI
        '
        Install.Enabled = False
        CancelCopy.Enabled = True
        '
        '-- Go
        '
        CopyBytesToFileMT()

    End Sub
    Private Sub CopyBytesToFileMT()
        '
        '-- Get work packet
        '
        Dim wp As WorkerPacket = taskList(0)
        '
        '-- Init progress bars
        '
        ProgressBarCurrent.Value = 0
        ProgressBarTotal.Value += 1
        '
        '-- Start worker
        '
        If Not _cancel Then
            Label1.Text = String.Format("Copying {0}...", Path.GetFileName(wp.Filename))
            bgCopier.RunWorkerAsync(wp)
        End If

    End Sub

    Private Sub DoWork(s As Object, e As DoWorkEventArgs) Handles bgCopier.DoWork

        Dim wp As WorkerPacket = CType(e.Argument, WorkerPacket)
        '
        '-- Calculate segments
        '
        '   note: byte().length returns integer which means we're limited to 2 Gb files
        '
        Dim length As Integer = wp.DataRef.Length
        Dim segments As Integer = CInt(Math.Floor(length / BufferSize))
        Dim leftOver As Integer = length - segments * BufferSize

        Dim bf As Integer = BufferSize
        If bf > length Then bf = length

        Dim fs As New FileStream(wp.Filename,
                                 FileMode.Create,
                                 FileAccess.Write,
                                 FileShare.None)
        '
        '-- Copy blocks
        '
        For i As Integer = 0 To segments - 1
            '
            '-- Cancelled?
            '
            If e.Cancel Then
                leftOver = 0
                Exit For
            End If
            '
            '-- Write a segment to file
            '
            Dim pos As Integer = i * BufferSize
            fs.Write(wp.DataRef, pos, bf)
            '
            '-- Report current progress
            '
            bgCopier.ReportProgress(CInt(pos / length * 100))

        Next
        '
        '-- Copy any remainer
        '
        If leftOver > 0 Then
            fs.Write(wp.DataRef, segments * BufferSize, leftOver)
            bgCopier.ReportProgress(100)
        End If
        '
        '-- Done
        '
        fs.Flush()
        fs.Dispose()

    End Sub
    Private Sub CopyProgress(s As Object, e As ProgressChangedEventArgs) Handles bgCopier.ProgressChanged

        ProgressBarCurrent.Value = e.ProgressPercentage

    End Sub
    Private Sub CopyCompleted(s As Object, e As RunWorkerCompletedEventArgs) Handles bgCopier.RunWorkerCompleted
        '
        '-- Remove task just finished
        '
        taskList.RemoveAt(0)
        '
        '-- Do we have another task?
        '
        If taskList.Count > 0 AndAlso Not _cancel Then
            CopyBytesToFileMT()
        Else
            If _cancel Then
                Label1.Text = "Cancelled by user."
            Else
                Label1.Text = "Completed!"
                '
                '-- Execute other tasks here...
                '
            End If
            '
            '-- Update UI
            '
            CancelCopy.Enabled = False
            Install.Enabled = True
        End If

    End Sub

End Class
更新:以下修改在复制任务完成后运行一个过程。根据需要修改

Imports System.ComponentModel
Imports System.IO
Imports System.Security

Public Class Form1

    Private Event AllCompleted()

    Private Const BufferSize As Integer = 4096

    Private WithEvents bgCopier As New BackgroundWorker
    Private WithEvents procUnzipper As New Process

    Private Class WorkerPacket
        Public DataRef As Byte()
        Public Filename As String
    End Class

    Private taskList As New List(Of WorkerPacket)
    Private _cancel As Boolean = False

    '
    '-- Setup worker
    '
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        bgCopier.WorkerReportsProgress = True
        bgCopier.WorkerSupportsCancellation = True

        procUnzipper.EnableRaisingEvents = True
        procUnzipper.SynchronizingObject = Me

    End Sub
    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        bgCopier.Dispose()
        procUnzipper.Dispose()

    End Sub
    '
    '-- UI
    '
    Private Sub Install_Click(sender As System.Object, e As System.EventArgs) Handles Install.Click
        '
        '-- This is where you initilize the paths and data you want to copy.
        '-- For this example I use the same data
        '
        AddCopyTask(My.Resources.TestData, "c:\test1.dat")
        AddCopyTask(My.Resources.TestData, "c:\test2.dat")
        AddCopyTask(My.Resources.TestData, "c:\test3.dat")

        StartCopyQue()

    End Sub
    Private Sub CancelCopy_Click(sender As System.Object, e As System.EventArgs) Handles CancelCopy.Click

        _cancel = True

        If bgCopier.IsBusy Then
            bgCopier.CancelAsync()
        End If

    End Sub
    '
    '-- The methods to build and perform task-list
    '
    Private Sub AddCopyTask(data As Byte(), filename As String)
        '
        '-- Create argument packet for worker
        '
        Dim wp As New WorkerPacket
        wp.DataRef = data
        wp.Filename = filename

        taskList.Add(wp)

    End Sub
    Private Sub StartCopyQue()
        '
        '-- Init total progressbar
        '
        ProgressBarTotal.Value = 0
        ProgressBarTotal.Maximum = taskList.Count

        _cancel = False

        '
        '-- Update UI
        '
        Install.Enabled = False
        CancelCopy.Enabled = True
        '
        '-- Go
        '
        CopyBytesToFileMT()

    End Sub
    Private Sub CopyBytesToFileMT()
        '
        '-- Get work packet
        '
        Dim wp As WorkerPacket = taskList(0)
        '
        '-- Init progress bars
        '
        ProgressBarCurrent.Value = 0
        ProgressBarTotal.Value += 1
        '
        '-- Start worker
        '
        If Not _cancel Then
            Label1.Text = String.Format("Copying {0}...", Path.GetFileName(wp.Filename))
            bgCopier.RunWorkerAsync(wp)
        End If

    End Sub

    Private Sub DoWork(s As Object, e As DoWorkEventArgs) Handles bgCopier.DoWork

        Dim wp As WorkerPacket = CType(e.Argument, WorkerPacket)
        '
        '-- Calculate segments
        '
        '   note: byte().length returns integer which means we're limited to 2 Gb files
        '
        Dim length As Integer = wp.DataRef.Length
        Dim segments As Integer = CInt(Math.Floor(length / BufferSize))
        Dim leftOver As Integer = length - segments * BufferSize

        Dim bf As Integer = BufferSize
        If bf > length Then bf = length

        Dim fs As New FileStream(wp.Filename,
                                 FileMode.Create,
                                 FileAccess.Write,
                                 FileShare.None)
        '
        '-- Copy blocks
        '
        For i As Integer = 0 To segments - 1
            '
            '-- Cancelled?
            '
            If e.Cancel Then
                leftOver = 0
                Exit For
            End If
            '
            '-- Write a segment to file
            '
            Dim pos As Integer = i * BufferSize
            fs.Write(wp.DataRef, pos, bf)
            '
            '-- Report current progress
            '
            bgCopier.ReportProgress(CInt(pos / length * 100))

        Next
        '
        '-- Copy any remainer
        '
        If leftOver > 0 Then
            fs.Write(wp.DataRef, segments * BufferSize, leftOver)
            bgCopier.ReportProgress(100)
        End If
        '
        '-- Done
        '
        fs.Flush()
        fs.Dispose()

    End Sub
    Private Sub CopyProgress(s As Object, e As ProgressChangedEventArgs) Handles bgCopier.ProgressChanged

        ProgressBarCurrent.Value = e.ProgressPercentage

    End Sub
    Private Sub CopyCompleted(s As Object, e As RunWorkerCompletedEventArgs) Handles bgCopier.RunWorkerCompleted
        '
        '-- Remove task just finished
        '
        taskList.RemoveAt(0)
        '
        '-- Do we have another task?
        '
        If taskList.Count > 0 AndAlso Not _cancel Then
            CopyBytesToFileMT()
        Else
            If _cancel Then
                Label1.Text = "Cancelled by user."
            Else
                Label1.Text = "Unzipping..."
                '
                '-- Start process
                '
                ProgressBarTotal.Style = ProgressBarStyle.Marquee

                Dim arg As String = String.Format(" x ""{0}"" -mmt -aoa -o ""{1}""",
                                                  "theZipFile.7z",
                                                  "installpath\")

                procUnzipper.StartInfo.FileName = "...\7z.exe"
                procUnzipper.StartInfo.Arguments = arg
                procUnzipper.Start()

            End If

        End If

    End Sub
    Private Sub UnzipCompleted(s As Object, e As EventArgs) Handles procUnzipper.Exited

        'just for example
        'this following require syncronizationobject set, see form_load
        RaiseEvent AllCompleted()

    End Sub
    Private Sub Done() Handles Me.AllCompleted
        '
        '-- Update UI
        '
        Label1.Text = "Completed!"

        ProgressBarTotal.Style = ProgressBarStyle.Blocks
        CancelCopy.Enabled = False
        Install.Enabled = True

    End Sub

End Class
这是实现你想要的方法之一。这种方法使UI处于独立状态,因此可以很好地进行更新。我编写了对两个进度条的支持,一个用于总进度(文件数),一个用于当前进度。代码支持取消

根据需要使用和修改,它是按原样提供的

代码假设如前所述,表单上有两个进度条以及两个按钮(安装和取消)-请参阅下面的快照

用法 您只需将要复制的所有资源添加到任务列表中,然后启动提示

AddCopyTask(resourceToCopy1, pathToWhereToCopy1)
AddCopyTask(resourceToCopy2, pathToWhereToCopy2)
...
StartCopyCue()
完整代码:

Imports System.ComponentModel
Imports System.IO

Public Class Form1

    'If you use small file sizes, lower this value to have progress-bar going
    Private Const BufferSize As Integer = 4096

    Private WithEvents bgCopier As New BackgroundWorker

    Private Class WorkerPacket
        Public DataRef As Byte()
        Public Filename As String
    End Class

    Private taskList As New List(Of WorkerPacket)
    Private _cancel As Boolean = False

    '
    '-- Setup worker
    '
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        bgCopier.WorkerReportsProgress = True
        bgCopier.WorkerSupportsCancellation = True

    End Sub
    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        If bgCopier IsNot Nothing Then
            bgCopier.Dispose()
        End If

    End Sub
    '
    '-- UI
    '
    Private Sub Install_Click(sender As System.Object, e As System.EventArgs) Handles Install.Click

        '
        '-- This is where you initilize the paths and data you want to copy.
        '-- For this example I use the same data
        '
        AddCopyTask(My.Resources.TestData, "c:\test1.dat")
        AddCopyTask(My.Resources.TestData, "c:\test2.dat")
        AddCopyTask(My.Resources.TestData, "c:\test3.dat")

        StartCopyCue()

    End Sub
    Private Sub CancelCopy_Click(sender As System.Object, e As System.EventArgs) Handles CancelCopy.Click

        _cancel = True

        If bgCopier.IsBusy Then
            bgCopier.CancelAsync()
        End If

    End Sub
    '
    '-- The methods to build and perform task-list
    '
    Private Sub AddCopyTask(data As Byte(), filename As String)
        '
        '-- Create argument packet for worker
        '
        Dim wp As New WorkerPacket
        wp.DataRef = data
        wp.Filename = filename

        taskList.Add(wp)

    End Sub
    Private Sub StartCopyCue()
        '
        '-- Init total progressbar
        '
        ProgressBarTotal.Value = 0
        ProgressBarTotal.Maximum = taskList.Count

        _cancel = False
        '
        '-- Update UI
        '
        Install.Enabled = False
        CancelCopy.Enabled = True
        '
        '-- Go
        '
        CopyBytesToFileMT()

    End Sub
    Private Sub CopyBytesToFileMT()
        '
        '-- Get work packet
        '
        Dim wp As WorkerPacket = taskList(0)
        '
        '-- Init progress bars
        '
        ProgressBarCurrent.Value = 0
        ProgressBarTotal.Value += 1
        '
        '-- Start worker
        '
        If Not _cancel Then
            Label1.Text = String.Format("Copying {0}...", Path.GetFileName(wp.Filename))
            bgCopier.RunWorkerAsync(wp)
        End If

    End Sub

    Private Sub DoWork(s As Object, e As DoWorkEventArgs) Handles bgCopier.DoWork

        Dim wp As WorkerPacket = CType(e.Argument, WorkerPacket)
        '
        '-- Calculate segments
        '
        '   note: byte().length returns integer which means we're limited to 2 Gb files
        '
        Dim length As Integer = wp.DataRef.Length
        Dim segments As Integer = CInt(Math.Floor(length / BufferSize))
        Dim leftOver As Integer = length - segments * BufferSize

        Dim bf As Integer = BufferSize
        If bf > length Then bf = length

        Dim fs As New FileStream(wp.Filename,
                                 FileMode.Create,
                                 FileAccess.Write,
                                 FileShare.None)
        '
        '-- Copy blocks
        '
        For i As Integer = 0 To segments - 1
            '
            '-- Cancelled?
            '
            If e.Cancel Then
                leftOver = 0
                Exit For
            End If
            '
            '-- Write a segment to file
            '
            Dim pos As Integer = i * BufferSize
            fs.Write(wp.DataRef, pos, bf)
            '
            '-- Report current progress
            '
            bgCopier.ReportProgress(CInt(pos / length * 100))

        Next
        '
        '-- Copy any remainer
        '
        If leftOver > 0 Then
            fs.Write(wp.DataRef, segments * BufferSize, leftOver)
            bgCopier.ReportProgress(100)
        End If
        '
        '-- Done
        '
        fs.Flush()
        fs.Dispose()

    End Sub
    Private Sub CopyProgress(s As Object, e As ProgressChangedEventArgs) Handles bgCopier.ProgressChanged

        ProgressBarCurrent.Value = e.ProgressPercentage

    End Sub
    Private Sub CopyCompleted(s As Object, e As RunWorkerCompletedEventArgs) Handles bgCopier.RunWorkerCompleted
        '
        '-- Remove task just finished
        '
        taskList.RemoveAt(0)
        '
        '-- Do we have another task?
        '
        If taskList.Count > 0 AndAlso Not _cancel Then
            CopyBytesToFileMT()
        Else
            If _cancel Then
                Label1.Text = "Cancelled by user."
            Else
                Label1.Text = "Completed!"
                '
                '-- Execute other tasks here...
                '
            End If
            '
            '-- Update UI
            '
            CancelCopy.Enabled = False
            Install.Enabled = True
        End If

    End Sub

End Class
更新:以下修改在cop之后运行一个过程