我的VB.Net应用程序出现了一个奇怪的挂起问题。当用户单击更新按钮时,以下内容将作为线程运行以对数据进行一些长时间的计算。它禁用控件,显示“工作中...”文本框,执行工作,重新启用控件,并摆脱“工作中...”文本框。偶尔(调试时从未复制过),用户窗口冻结并挂起。发生这种情况时,CPU使用率是0,因此可以完成计算,但是控件仍然显示为已禁用,并且“正在运行...”文本框仍然可见,尽管窗口完全卡住了并且不会更新。这将无限期保持这种状态(用户尝试等待长达30分钟)。奇怪的是,我只能通过从任务栏上的窗口右键菜单中单击“最小化/还原”按钮来“取消粘帖”该窗口。短暂的延迟后, window 就会恢复原状。窗口本身的最小化/还原似乎没有作用。

所以我的问题是,我在下面的线程中做错了什么?

Dim Thread As New Threading.Thread(AddressOf SubDoPriceUpdateThread)
Thread.Start()

线:
    Private Sub SubDoPriceUpdateThread()

            Dim Loading As New TextBox
            Try
                CntQuotePriceSummary1.Invoke(New Action(Of Control)(AddressOf CntQuotePriceSummary1.Controls.Add), Loading)
                CntQuotePriceSummary1.Invoke(New Action(Sub() CntQuotePriceSummary1.Enabled = False))

                Loading.Invoke(New Action(AddressOf Loading.BringToFront))
                Loading.Invoke(New Action(Sub() Loading.Text = "Working..."))

                '***Long running calculations***

                Invoke(New Action(AddressOf FillForm))

            Finally
                CntQuotePriceSummary1.Invoke(New Action(Of Control)(AddressOf CntQuotePriceSummary1.Controls.Remove), Loading)
                CntQuotePriceSummary1.Invoke(New Action(Sub() CntQuotePriceSummary1.Enabled = True))
                Loading.Invoke(New Action(AddressOf Loading.Dispose))
            End Try

    End Sub

最佳答案

根据Hans的评论,很明显,没有在UI线程上创建Loading文本框,而这正是导致死锁问题的原因。我已经重写了代码。

     Private Sub SubDoPriceUpdateThread()

            Dim Loading As TextBox
            Invoke(Sub() Loading = New TextBox)

            Try
               Invoke(Sub()
                           CntQuotePriceSummary1.Controls.Add(Loading)
                           CntQuotePriceSummary1.Enabled = False
                           Loading.BringToFront()
                           Loading.Text = "Working..."
                       End Sub)

               '***Long running calculations***

                Invoke(Sub() FillForm())

            Finally
                Invoke(Sub()
                           CntQuotePriceSummary1.Controls.Remove(Loading)
                           CntQuotePriceSummary1.Enabled = True
                           Loading.Hide()
                           Loading.Dispose()
                       End Sub)
            End Try

    End Sub

09-26 19:47
查看更多