【发布时间】:2023-03-30 21:33:01
【问题描述】:
在我的 Form1 类中,我有一个名为 beginProcessingItems() 的方法,它对项目列表进行操作。这个列表可能非常大,所以我在一个新线程中执行 beginProcessingItems 方法,如下所示:
Dim processThread As New Thread(AddressOf beginProcessingItems)
processThread.Start()
有时我需要显示一个对话框来从用户那里收集有关某个项目的其他信息。此对话框是在 beginProcessingItems() 方法中创建和打开的,该方法现在在与我的 Form1 窗口不同的线程中运行。
当我打开对话框时,它正在 Form1 窗口后面加载。我在其他堆栈帖子中尝试了各种建议,但最终都导致跨线程操作无效异常。
这是我当前必须打开对话框的代码:
Public Sub beginProcessingItems()
' ..do stuff .. and sometimes:
Dim IDD As New ItemDetailsDialog()
IDD.Location = ImportItemsButton.Location ' sets X,Y coords
IDD.StartPosition = FormStartPosition.Manual
IDD.TopMost = True
'Note: Me = The Form1 object
'IDD.Parent = Me '<-- also throws exception.
If IDD.ShowDialog(Me) = DialogResult.OK Then ' <-- If I remove "Me" then the dialog opens but its underneath the Form1 window.
' .. do stuff with the dialog results
End If
End Sub
这是异常消息:
跨线程操作无效:控件“Form1”从 线程不是创建它的线程。
【问题讨论】:
-
是的,一旦您开始尝试进行任何类型的 UI 交互,您就会 100% 遇到后台线程问题。您确实需要通过您的收集所有要求并将其传递到线程中。或者,也许迁移到更新的 Async/Await 模式可能会简化您的 UI 要求
标签: .net vb.net multithreading winforms dialog