|
Cross-thread operation not valid: Control 'lblCounter1' accessed from a thread other than the thread it was created on.
This is a common problem. I will provide solution with an example
This is a simple WinForm with two labels
Below is the working code to update the lables using a thread.
Here the main point u have to see is that. controls in the main forms cant be updated from another thread. to do it we use an invoke
Control.Invoke Method (Delegate) (System.Windows.Forms)
Executes the specified delegate on the thread that owns the control's underlying window handle.
Here are more details on invoke
Delegates are similar to function pointers in C or C++ languages. Delegates encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that calls the referenced method, and the method to be invoked can be unknown at compile time. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and more secure.
The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception. Exceptions that are raised during the call will be propagated back to the caller.
Public oThread As System.Threading.Thread
Public strThread As String = ""
Public strSelector As String = ""
Public Sub ThreadWrite()
Select Case strSelector
Case "Counter1"
lblCounter1.Text = strThread
Case "Counter2"
lblCounter2.Text = strThread
End Select
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
oThread = New System.Threading.Thread(AddressOf ThreadCode)
End Sub
Public i As Integer = 0
Public j As Integer = 0
Public bFlag As Integer = 0
Private Sub ThreadCode()
Do While True
strSelector = "Counter1"
strThread = i.ToString
lblCounter1.Invoke(New MethodInvoker(AddressOf ThreadWrite))
strSelector = "Counter2"
strThread = j.ToString
lblCounter1.Invoke(New MethodInvoker(AddressOf ThreadWrite))
bFlag = bFlag + 1
If bFlag = 2 Then
bFlag = 0
j = j + 1
End If
i = i + 1
System.Threading.Thread.Sleep(500)
Loop
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
oThread.Start()
End Sub
|