Status Strip Thread Error

Sabour

Active member
Joined
Sep 1, 2006
Messages
25
Programming Experience
Beginner
How to make a thread when setting statusstrip1.text? i have 2 toolstrip,i can set for the first one but somehow when statusstrip2.text value changed i always got this :
VB.NET:
Error : Cross-thread operation not valid: Control 'StatusStrip1' accessed from a thread other than the thread it was created on.
 
You have to invoke method by a delegate on the thread that created the control.

There is some information in documentation on multi-threading and how to make thread-safe calls.

Here is a simple example setting the Text property of a Textbox from a different thread than the one that created this control. The updateUI method is called from that thread with the text parameter, what happens then is that the control is checked for InvokeRequired and if so creates a new delegate pointing to this method and invokes it with the Invoke call on the thread that created the control.
VB.NET:
Private Delegate Sub dlgUpdateUI(ByVal text As String)
 
Sub updateUI(ByVal text As String)
If TextBox1.InvokeRequired = True Then
  Dim d As New dlgUpdateUI(AddressOf updateUI)
  TextBox1.Invoke(d, text)
Else
  TextBox1.Text = text
End If
End Sub
You can make methods like this more or less dynamic to handle different types of parameters, controls and properties that need to be operated across different threads, for instance using reflection, or structurally reusing delegates. Reflection is not very fast and have to be used with care, sometimes it is better to create several methods. Here is one example where you dynamically and thread-safe can set any single property for any control:
VB.NET:
Private Delegate Sub dlgUpdateUIgen(ByVal ctrl As Control, ByVal prop As String, ByVal value As Object)
 
Private Sub updateUIgen(ByVal ctrl As Control, ByVal prop As String, ByVal value As Object)
If ctrl.InvokeRequired = True Then
  Dim d As New dlgUpdateUIgen(AddressOf updateUIgen)
  ctrl.Invoke(d, ctrl, prop, value)
Else
  ctrl.GetType.GetProperty(prop).SetValue(ctrl, value, Nothing)
End If
End Sub
This version would be called like this:
VB.NET:
Sub threaded()
  updateUIgen(TextBox1, "Text", "my text")
  updateUIgen(TextBox1, "BackColor", Color.Red)
End Sub
 
Back
Top