0

我有一个调用表单的后台工作人员,拿着一个 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
4

1 回答 1

1

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

尝试切换按钮单击功能中的内容和 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()取决于您希望过程是模态的还是非模态的。您可以在此处阅读更多相关信息。

于 2013-02-03T22:26:20.717 回答