任务未关闭等待表单



我正在使用一些任务来做一些操作,同时我向用户显示额外的"等待表单",然后当任务的功能完成时,欢迎表单从任务中关闭。我已经有了解决方案,它在本主题中进行了讨论:在此处输入链接描述

现在的问题是,我想在其他地方实施它,我面临的问题是我的等待表仍然在(没有关闭),我不知道为什么。我能说的是,我检查了函数是否在检索值——这是肯定的。我想这是因为函数在欢迎表单出现之前就完成了,所以它会堆叠。。。如果是这样的话,有什么可以检查的吗?这就是代码:

 Dim pic As New Waiting
                Dim tsk As Task(Of Boolean) = Task.Factory.StartNew(Function()
                                                                        '--Run lenghty task
                                                                        '--Show the form
                                                                        pic.ShowDialog()
                                                                        Dim retValue As Boolean = THIS_UpdateTransport()
                                                                        '--Close form once done (on GUI thread)
                                                                        pic.Invoke(New Action(Sub() pic.Close()))
                                                                        Return retValue
                                                                    End Function)

                '--Show the form
                pic.ShowDialog()
                Task.WaitAll(tsk

)

以下是我在长任务运行时使用.Show()而不是ShowDialog()阻塞主窗体的答案:

  1. THIS_UpdateTransport更改为THIS_UpdateTransportAsync

       Private Function THIS_UpdateTransportAsync() As Task(Of Boolean)
            'Do some really important work
            Return Task.Factory.StartNew(Function()
                                                 Threading.Thread.Sleep(5000)
                                                 Return True
                                         End Function)
        End Function
    
  2. 将调用Task的UI方法声明为async(在我的示例中单击按钮):

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim pic As New Waiting()
        'Block Parent Form from all user interactions
        Me.Enabled = False         
        'Use Show() instead of ShowDialog() to avoid Thread blocking
        pic.Show(Me) 
        'Await the long running Task until its done
        Dim result As Boolean = Await THIS_UpdateTransportAsync()
        'Close Waiting window
        pic.Close()
        'Reactivating Parent Form and enable use interactions
        Me.Activate()
        Me.Enabled = True
    End Sub
    

所以这对我和一些示例窗体+控件都有效。

最新更新