JHall
JHall

Reputation: 93

VB form cross thread method call with parameters

I am writing a VB form application that redirects the standard output stream of a process and uses it in a UI.

I am having trouble calling methods with parameters that update controls on the form from the OutputHandler sub.

I can call a method without parameters like so

Me.Invoke(New MyDelSub(AddressOf ServerStarted))

Which works fine.

And a bit of googling told me that to call a method with parameters I should do this:

Dim del As JoinDelegate = AddressOf PlayerJoins
del.Invoke(username)

With this delegate and method pair:

Private Delegate Sub JoinDelegate(ByVal username As String)
Private Sub PlayerJoins(ByVal username As String)
   PlayersBox.Items.Add(username)
   'Do other stuff
End Sub

But this produces an IllegalOperationException the first time the method tries to access a control.

Upvotes: 2

Views: 6448

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

E.g.

Private Sub SetControlText(control As Control, text As String)
    If control.InvokeRequired Then
        control.Invoke(New Func(Of Control, String)(AddressOf SetControlText), control, text)
    Else
        control.Text = text
    End If
End Sub

Call that method from any thread.

Upvotes: 0

Reza Aghaei
Reza Aghaei

Reputation: 125197

1) Supposing you have a method like this:

Public Sub DoSomething(value1 As String, value2 As String)
    MessageBox.Show(String.Format("{0} {1}", value1, value2))
End Sub

You can call it using invoke this way:

Me.Invoke(Sub() DoSomething("Hello", "World!"))

2) If you want to make thread safe call to a control you can write the method this way:

Public Sub AddItemToListBox1(item As String)
    If (ListBox1.InvokeRequired) Then
        ListBox1.Invoke(Sub() AddItemToListBox1(item))
    Else
        ListBox1.Items.Add(item)
    End If
End Sub

Then it's enough to call it in a the UI thread or in another thread the same way simply:

AddItemToListBox1("some item")

The call would be thread safe.

Upvotes: 6

Related Questions