When accessing controls from another thread you must typically invoke the accessing/updating of the control. This is done to synchronize the updating of the controls, so that two threads does not update one control at the same time.
You can think of it like this: two people cannot write at the same paper at the same time.
Invocation is usually nothing hard. It's basically just doing these two things:
- Check if invocation is required by the control or it's container.
- Invoke if necessary.
Invocation is performed using Delegate methods. If you target .NET Framework 4.0 or higher you can use the Sub()
lambda expression to create a very simple delegate.
Public Sub FZConsole()
While True
If Form1.InvokeRequired = True Then 'Invocation is required.'
Form1.Invoke(Sub() Form1.Richtextbox1.AppendText(Environment.NewLine & "Test From Class"))
Else 'Invocation is not required.'
Form1.Richtextbox1.AppendText(Environment.NewLine & "Test From Class")
End If
Threading.Thread.Sleep(1)
End While
End Sub
However if you target .NET Framework 3.5 or lower things become a little trickier. When targeting an earlier framework you have to declare the delegate yourself, and it's not as simple as using the lambda since it works differently when passing variables.
Delegate Sub TextUpdaterDelegate(ByVal Text As String)
Public Sub FZConsole()
While True
If Form1.InvokeRequired = True Then 'Invocation is required.'
Form1.Invoke(New TextUpdaterDelegate(AddressOf RichTextBox1.AppendText), Environment.NewLine & "Test From Class")
Else 'Invocation is not required.'
Form1.Richtextbox1.AppendText(Environment.NewLine & "Test From Class")
End If
Threading.Thread.Sleep(1)
End While
End Sub