views:

172

answers:

1

I don't get it. If I want to change the text on a button from a thread other than the UI thread in Visual Basic .NET, I need to use a delegate, and do something along the lines of

 Private Delegate Sub SetTextDelegate(ByVal TheText As String)
 Private Sub delSetText(ByVal TheText As String)
     Button1.Text = TheText
 End Sub

 Private Sub ChangeText(ByVal TheText As String)
     If Button1.InvokeRequired Then
         Me.BeginInvoke(New SetTextDelegate(AddressOf delSetText), TheText)
     Else
         delSetText(TheText)
     End If
 End Sub

Of course I can make more generic functions that aren't so hard-wired. But still, it seems like a lot of typing. Am I doing this in a roundabout way? How is this not included in the control properties---why would anyone leave this up to the programmer if it is required?

+1  A: 

In C#, anonymous methods are very helpful here; perhaps there is something similar in VB? (my VB-fu is weak). You might also re-use the current method rather than have two; as an example:

void ChangeText(string text) {
    if(InvokeRequired) {
        this.Invoke((MethodInvoker) delegate {ChangeText(text);});
    } else {
        Button1.Text = text;
    }
}

Note that I've used MethodInvoker here deliberately - this is handled as a special case by Invoke, meaning it doesn't have to use the (very slow) DynamicInvoke.

I could also have done the .Text = text in the anon method, but that seems to violate DRY.

Marc Gravell
I should have switched to C# a long time ago. But VB is a hard habit to break. Thanks.
pelesl