JHall JHall - 4 months ago 42
Vb.net Question

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

With this delegate and method pair:

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

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


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))
    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.