如何在线程中添加hander?

时间:2016-04-07 09:33:47

标签: vb.net multithreading zipfile

我在VB中使用Ionic Class压缩文件。我想向GUI报告保存进度。我使用 Sub ProgessChanged 处理了 zip.SaveProgress 事件。它在主线程上工作,但我需要将它转移到工作线程。

这就是我绑的......

Dim foldertozip As String
Dim zipfileaddress As String

 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectFile_BT.Click
      Dim th As Thread = New Thread(AddressOf ZipUp)
      th.Start()
 End Sub

Public Sub ZipUp()
    Dim zip As ZipFile = New ZipFile
    AddHandler zip.SaveProgress, AddressOf ProgressUpdater

    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed
    zip.BufferSize = My.Settings.BufferSize
    zip.AddDirectory(foldertozip)
    zip.Save(zipfileaddress)
End Sub


Public Shared Sub ProgressUpdater(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
    If (e.EventType = ZipProgressEventType.Saving_Completed) Then
        Return
    ElseIf (e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry) Then
        Status.Label1.Text = e.CurrentEntry.FileName
    ElseIf (e.EventType = ZipProgressEventType.Saving_EntryBytesRead) Then
        Status.PercentLabel.Text = CStr(CInt(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer))
        Status.ProgressBar1.Value = CInt(CInt(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer))
    End If
End Sub

我对线程不太熟悉......

由于

1 个答案:

答案 0 :(得分:2)

你是说,实际上没有说,你想在辅助线程上进行压缩但是在UI线程上处理事件?如果是这样,那么您只需使用相同的Invoke方法在UI线程上执行事件处理程序,就像在WinForms中的UI线程上执行方法时一样。无论如何,都会在辅助线程上引发该事件。

Public Sub ProgressUpdater(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
    If Me.InvokeRequired Then
        Me.Invoke(New Action(Of Object, SaveProgressEventArgs)(AddressOf ProgressUpdater), sender, e)
    Else
        If (e.EventType = ZipProgressEventType.Saving_Completed) Then
            Return
        ElseIf (e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry) Then
            Status.Label1.Text = e.CurrentEntry.FileName
        ElseIf (e.EventType = ZipProgressEventType.Saving_EntryBytesRead) Then
            Status.PercentLabel.Text = CStr(CInt(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer))
            Status.ProgressBar1.Value = CInt(CInt(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer))
        End If
    End If
End Sub

请注意,该方法不是Shared,因此它可以访问当前实例的成员。