Is it possible to modify the properties of a forms controls from another thread without creating a separate method and delegate for each property that you want to modify?
I am currently writing a multithreaded application where I need background threads to manipulate the userinterface. I feel like the amount of code that I am writing to do simple tasks such as setting a control's text property is huge compared to the code I would write for a single threaded app.
In a single threaded app, one can simply use Control.text = "My Text", but so far when creating a multithreaded application, I need all of the following just to perform the same task in a thread safe way.
Delegate Sub ChangeTextDelegate(ByVal ctrl As Control, ByVal str As String)
Private Sub ChangeText(ByVal ctrl As Control, ByVal str As String)
If ctrl.InvokeRequired Then
ctrl.Invoke(New ChangeTextDelegate(AddressOf ChangeText), New Object() {ctrl, str})
Return
End If
ctrl.Text = str
End Sub
I have plenty of similar code that seems equally long for such simple tasks:
Delegate Sub ChangeVisibilityDelegate(ByVal ctrl As Control, ByVal bool As Boolean)
Private Sub ChangeVisibility(ByVal ctrl As Control, ByVal bool As Boolean)
If ctrl.InvokeRequired Then
ctrl.Invoke(New ChangeVisibilityDelegate(AddressOf ChangeVisibility), New Object() {ctrl, bool})
Return
End If
ctrl.Visible = bool
End Sub
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…