Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net accessed from a thread other than the thread it was created on

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

like image 936
babboon Avatar asked Nov 08 '13 11:11

babboon


People also ask

Why do I get a threading error in Visual Studio?

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:

How do I call a Windows Forms control from another thread?

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.

What happens if you have two threads in an app?

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.

What is cross-thread operation not valid in Visual Studio?

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:


1 Answers

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
like image 110
Szymon Avatar answered Sep 19 '22 13:09

Szymon