处置后台工作者不起作用

时间:2013-02-03 14:01:13

标签: vb.net backgroundworker

我有一个后台工作者调用一个表单,持有一个gif动画。目的是在进程正在进行时显示动画,但是在进程完成时它应该关闭。但即使在完成该过程后它也不会关闭。请帮忙。
感谢

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    frmAnimation.ShowDialog()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    BackgroundWorker1.RunWorkerAsync()
    Dim sqldatasourceenumerator1 As SqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance
    datatable1 = sqldatasourceenumerator1.GetDataSources()
    DataGridView1.DataSource = datatable1

    'I have tried CancelAsync, but did not work

    BackgroundWorker1.CancelAsync()
    frmAnimation.Dispose()
End Sub

1 个答案:

答案 0 :(得分:1)

BackgroundWorkers旨在实际执行后台操作的“工作”,因此主UI线程可以继续将内容渲染到屏幕上。我怀疑你希望在BackgroundWorker线程中完成GetDataSources()函数调用。

尝试切换按钮单击功能中的内容以及BackgroundWorker的DoWork功能中的内容。具体来说,我的意思是这样的:

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim sqldatasourceenumerator1 As SqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance
            datatable1 = sqldatasourceenumerator1.GetDataSources()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            BackgroundWorker1.RunWorkerAsync()
            frmAnimation.ShowDialog()
    End Sub

此外,在RunWorkerCompleted事件中添加一些代码,以处理完成后台操作时应该执行的操作。

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
            DataGridView1.DataSource = datatable1
            frmAnimation.Close()
    End Sub

您可能还需要考虑使用frmAnimation.Show()而不是frmAnimation.ShowDialog(),具体取决于您是希望程序是模态还是无模式。您可以阅读有关here的更多信息。