windows - 运行线程时窗口偶尔会挂起/卡住

标签 windows vb.net multithreading dispose invoke

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

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

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 的评论,很明显 Loading 文本框不是在 UI 线程上创建的,这就是导致死锁问题的原因。我已经重写了代码。

     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

关于windows - 运行线程时窗口偶尔会挂起/卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14362123/

相关文章:

C++11 多线程 : Valgrind uninitialized value(s) warning

windows - 如何使用特定的图形驱动程序创建 OpenGL 上下文?

vb.net - 如何在 VB.NET 中进行按位与运算?

mysql - 如何使用 vb.net 与不同的字符串输入进行比较,在 mysql 中使用 LIKE 子句进行查询?

vb.net - 在 Using 语句中通过工厂创建一次性对象

java - 线程在 notifyall() 之后没有返回

c# - ManagedThreadID与操作系统ThreadID的关系

python - 有没有办法模拟 Windows alt-tabbing?

c++ - 如何阻止 LWA_COLORKEY 绘制灰色轮廓?

windows - GNU CC 和 Windows