S
Samuel R. Neff
I'm trying to find a good way to handle Control.InvokeRequired without
duplicating four lines of code in every function/event. Typically
what I've seen in books is this:
If InvokeRequired Then
Invoke(new EventHandler(AddressOf thisFunc), new Object() { sender,
e})
Return
End If
At the start of every function. Is there a good way to extract these
four lines of code from the functions themselves? I figured I can
make an InvokeIfRequired function but I would still need three lines
in order to accomodate the Return.
The best I could come up with is to get at it from the sending side
and not the receiving side (code below) but that it feels like the
handler should be taking care of this and not the sender (ideally, the
framework would take care of it internally for events).
Also the downside to the sub I came up with is that you lose
compile-time checking on arguments.
other options?
Thanks,
Sam
Public Shared Sub SmartRaiseEvent( _
ByVal delegat As [Delegate], _
ByVal args As Object(), _
ByVal synchronous As Boolean)
For Each iDelegate As [Delegate] In _
delegat.GetInvocationList()
Dim target As Object = iDelegate.Target
If Not target Is Nothing AndAlso _
TypeOf target Is Control AndAlso _
DirectCast(target, Control).InvokeRequired Then
If synchronous Then
DirectCast(target, Control).Invoke(iDelegate, args)
Else
DirectCast(target, Control).BeginInvoke(iDelegate, args)
End If
Else
iDelegate.DynamicInvoke(args)
End If
Next
End Sub
duplicating four lines of code in every function/event. Typically
what I've seen in books is this:
If InvokeRequired Then
Invoke(new EventHandler(AddressOf thisFunc), new Object() { sender,
e})
Return
End If
At the start of every function. Is there a good way to extract these
four lines of code from the functions themselves? I figured I can
make an InvokeIfRequired function but I would still need three lines
in order to accomodate the Return.
The best I could come up with is to get at it from the sending side
and not the receiving side (code below) but that it feels like the
handler should be taking care of this and not the sender (ideally, the
framework would take care of it internally for events).
Also the downside to the sub I came up with is that you lose
compile-time checking on arguments.
other options?
Thanks,
Sam
Public Shared Sub SmartRaiseEvent( _
ByVal delegat As [Delegate], _
ByVal args As Object(), _
ByVal synchronous As Boolean)
For Each iDelegate As [Delegate] In _
delegat.GetInvocationList()
Dim target As Object = iDelegate.Target
If Not target Is Nothing AndAlso _
TypeOf target Is Control AndAlso _
DirectCast(target, Control).InvokeRequired Then
If synchronous Then
DirectCast(target, Control).Invoke(iDelegate, args)
Else
DirectCast(target, Control).BeginInvoke(iDelegate, args)
End If
Else
iDelegate.DynamicInvoke(args)
End If
Next
End Sub