VB.NET 2010, .NET 4
Hello,
I recently read about using SynchronizationContext objects to control the execution thread for some code. I have been using a generic subroutine to handle (possibly) cross-thread calls for things like updating UI controls that utilizes Invoke. I'm an amateur and have a hard time understanding the pros and cons of any particular approach. I am looking for some insight on which approach might be preferable and why.
Update: This question is motivated, in part, by statements such as the following from the MSDN page on Control.InvokeRequired.
An even better solution is to use the
SynchronizationContext returned by
SynchronizationContext rather than a
control for cross-thread marshaling.
Method 1:
Public Sub InvokeControl(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of T))
If Control.InvokeRequired Then
Control.Invoke(New Action(Of T, Action(Of T))(AddressOf InvokeControl), New Object() {Control, Action})
Else
Action(Control)
End If
End Sub
Method 2:
Public Sub UIAction(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of Control))
SyncContext.Send(New Threading.SendOrPostCallback(Sub() Action(Control)), Nothing)
End Sub
Where SyncContext is a Threading.SynchronizationContext object defined in the constructor of my UI form:
Public Sub New()
InitializeComponent()
SyncContext = WindowsFormsSynchronizationContext.Current
End Sub
Then, if I wanted to update a control (e.g., Label1) on the UI form, I would do:
InvokeControl(Label1, Sub(x) x.Text = "hello")
or
UIAction(Label1, Sub(x) x.Text = "hello")
So, what do y'all think? Is one way preferred or does it depend on the context? If you have the time, verbosity would be appreciated!
Thanks in advance,
Brian