在我的 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”。
uj5u.com熱心網友回復:
我能夠將代碼編入使用委托作業的東西中。
在 Form1 類中,我添加了:
' = Created a public property to hold the dialog object ======
Public IDD As ItemDetailDialog = Nothing
' = Created a Delegate ======
Delegate Sub DelegateShowItemDetailDialog(ByVal Param1 As Integer, ByRef SomeClassObj As SomeClass, ByVal Param3 As Integer)
' = Created a method that instantiates the IDD property and shows the dialog =====
Private Sub ShowItemDetailDialog(ByVal Param1 As Integer, ByRef SomeClassObj As SomeClass, ByVal Param3 As Integer)
IDD = New ItemDetailDialog(Param1, SomeClassObj, Param3)
IDD.Location = ImportItemsButton.Location ' sets X,Y coords
IDD.StartPosition = FormStartPosition.Manual
'IDD.TopMost = True ' <-- not needed
'IDD.Parent = Me ' <-- not needed
IDD.ShowDialog()
End Sub
' = Instantiate the Delegate object into a public property
' = that will get invoked from the beginProcessingItems() method running in a separate thread
Public ThreadShowItemDetailDialog As New DelegateShowItemDetailDialog(AddressOf ShowItemDetailDialog)
我修改了 beginProcessingItems 方法如下:
Public Sub beginProcessingItems()
' ..do stuff .. and sometimes:
Me.Invoke(ThreadShowItemDetailsDialog, {Param1, SomeClassObj, Param3})
' dialog is now on top of the form1 window :-)
If IDD.DialogResult = DialogResult.OK Then
' .. do stuff with the dialog results via the IDD class object
End If
End Sub
請注意,Param1、SomeClassObj 和 Param3 變數顯示為如何將引數值傳遞給對話框物件的示例。顯然,您可以將它們更改為對話框物件實體化器需要的任何內容。
uj5u.com熱心網友回復:
嘗試將其放入您的 Sub Form_Load 中:
CheckForIllegalCrossThreadCalls = False
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/341381.html
