I am trying to set text to label Label_caller.Text = phone_number
and I get this error: "System.InvalidOperationException: Cross-thread operation not valid: Control 'Label_caller' accessed from a thread other than the thread it was created on." How do I overcome this problem? How do I use keyword Me.?
This error occurs when trying to perform operations on a windows control when using threading. Here we will go through the error and how to resolve it. We will create a Windows Forms app in Visual Studio:
There are two ways to safely call a Windows Forms control from a thread that didn't create that control. Use the System.Windows.Forms.Control.Invoke method to call a delegate created in the main thread, which in turn calls the control.
Two or more threads manipulating a control can force the control into an inconsistent state and lead to race conditions, deadlocks, and freezes or hangs. If you implement multithreading in your app, be sure to call cross-thread controls in a thread-safe way. For more information, see Managed threading best practices.
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. This error occurs when trying to perform operations on a windows control when using threading. Here we will go through the error and how to resolve it. We will create a Windows Forms app in Visual Studio:
In Windows, you can access UI elements only on the UI thread. For that reason, if you need to access them from another thread, you may need to invoke that action on the UI thread.
You need to use the following method to update the text box. This will check if invoking on the main thread is required and if needed, call the same method on the UI thread.
Private Sub UpdateTextBox(ByVal phone_number As String)
If Me.InvokeRequired Then
Dim args() As String = {phone_number}
Me.Invoke(New Action(Of String)(AddressOf UpdateTextBox), args)
Return
End IF
Label_caller.Text = phone_number
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With