自从我工作在Winform应用程序以来一直如此。我的专业一直在与Asp.net/Websites合作。最近,我获得了一个应用程序,可以从.Net 1.1升级到.Net 4.6。该应用程序是一个MDI应用程序,它在跨线程操作时遇到问题。具体来说,当点击用户控件中的按钮事件时,意图是显示主MDIchild表单(cfrmOverview),但是由于禁止访问名为picDisplay的Picturebox控件,因此会发生错误。即使添加了代码,我仍然收到错误。我选择退出使用CheckForIllegalCrossThreadCalls,因为它会影响程序和MSDN建议的其他部分。 Insight需要。通过usercontrol .net 1.1到4.6之间的父级和子级之间的MDI跨线程异常通过按钮.net 1.1到4.6
Public Delegate Sub Mydelegate(ByVal AControl As PictureBox)
Public Shared Sub CreateEnableControl(ByVal AControl As PictureBox)
AControl.Visible = True
AControl.Enabled = True
End Sub
Public Shared Sub NavigateTo(ByVal sender As System.Windows.Forms.UserControl, ByVal aNavTarget As String, Optional ByVal param As Object = Nothing)
Dim aType As Type
Dim Types() As Type
Dim aobject As Object
Try
If IsNothing(System.Reflection.Assembly.GetEntryAssembly) Then
aobject = sender.ParentForm
Types = System.Reflection.Assembly.GetAssembly(aobject.GetType).GetTypes
Else
Types = System.Reflection.Assembly.GetEntryAssembly.GetTypes
End If
Dim aForm As Windows.Forms.Form
For Each aType In Types
If aType.BaseType Is GetType(MdiChild) Then
If aType.Name = aNavTarget Then
Dim aMdiParent As Windows.Forms.Form
If TypeOf (sender.ParentForm) Is MdiParent Then
aMdiParent = sender.ParentForm
Else
aMdiParent = sender.ParentForm.ParentForm
End If
For Each aForm In aMdiParent.MdiChildren
If aType.FullName Is aForm.GetType.FullName Then
aForm.Tag = param
'Added Code below to try to prevent Cross-Thread exception on PicDisplay found in the Main cfrmOverview Form
'that has designed time user control embedded.
'New Code Start----------------------------------------------------------------------
For Each aControl As Windows.Forms.Control In aForm.Controls.Find("picDisplay", True)
If aControl.InvokeRequired Then
Dim myArray(0) As Object
myArray(0) = New PictureBox
aControl.BeginInvoke(New Mydelegate(AddressOf CreateEnableControl), myArray)
End If
Next
'New Code End------------------------------------------------------------------------
aForm.Show() 'Cross-thread exception for picDisplay is here.
GoTo Success
End If
您正在测试'InvokeRequired'并在该代码中调用'BeginInvoke'的事实表明它将会或可能不会在UI线程上执行。这意味着它不应该访问该代码中的任何表单或其他控件的任何成员。 'aForm'的'Show'方法是一个表单的成员,所以它是不受限制的。你需要做一个类似的测试,并调用在UI线程上调用该窗体上的“Show”。 – jmcilhinney