触发后台工作完成事件

时间:2010-06-17 19:30:13

标签: vb.net progress-bar background-process

我正在尝试以单独的形式(progressForm)显示进度条(marque),而我在后台进行一些计算。

我知道这样做的典型方法是在后台工作程序中包含计算并在主线程中显示progressForm。这种方法在我的应用程序中会导致很多同步问题,因此我在后台工作进程中使用progressForm.ShowDialog()显示progressForm。但我需要在应用程序中触发Completed事件以关闭表单。

这可能吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

一旦您的后台工作人员的进度达到100%,后台工作人员的RunWorkerCompleted事件就会触发。

修改 - 添加了代码示例

    Dim WithEvents bgWorker As New BackgroundWorker With { _
    .WorkerReportsProgress = True, _
    .WorkerSupportsCancellation = True}

    Private Sub bgWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork
        For i As Integer = 0 To 100
            'Threw in the thread.sleep to illustrate what's going on.  Otherwise, it happens too fast.
            Threading.Thread.Sleep(250)
            bgWorker.ReportProgress(i)
        Next
    End Sub

    Private Sub bgWorker_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgWorker.ProgressChanged
        If e.ProgressPercentage Mod 10 = 0 Then
            MsgBox(e.ProgressPercentage.ToString)
        End If
    End Sub

    Private Sub bgWorker_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgWorker.RunWorkerCompleted
        MsgBox("Done")
    End Sub