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.?
Asked
Active
Viewed 1.2k times
10

babboon
- 683
- 3
- 20
- 45
-
1pass Label_caller label as argument to thread modifying its text – Ali Kazmi Nov 08 '13 at 12:00
-
1possible duplicate of [VB.NET Cross-thread operation not valid](http://stackoverflow.com/questions/7296564/vb-net-cross-thread-operation-not-valid) – J... Nov 08 '13 at 12:01
-
2This is probably THE most common question on StackOverflow. Searching isn't that hard... http://stackoverflow.com/search?q=[vb.net]+Cross-thread+operation+not+valid – J... Nov 08 '13 at 12:02
-
http://msdn.microsoft.com/en-us/library/ms171728.aspx – J... Nov 08 '13 at 12:03
2 Answers
21
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

Szymon
- 42,577
- 16
- 96
- 114
0
I am probably answering quite late but adding following code in form load event seems solving problem.
Not sure though it's perfect answer or not:
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False

Shital
- 207
- 2
- 12
-
4That doesn't actually solve the problem, it just obfuscates it and makes it much, much worse... – Taegost Oct 18 '17 at 15:43
-
@Taegost The question was "How do I overcome this problem?" not "How do I make safe, cross thread calls" so, this answer while it may not be the safest way to overcome the problem, is still a perfectly valid answer and does indeed overcome the problem and shouldn't be down-voted for that, especially since the same answer passed just fine on an identical C# post: https://stackoverflow.com/a/38784153/6136296 – Shayna Jan 27 '19 at 03:56
-
1@Shayna - This doesn't overcome the problem, it hides it. It will likely cause the application to break in other ways, and more than likely, make that part of the code not work as expected. This is a terrible practice that should never be taught to new programmers as a resolution to an error. – Taegost Jan 28 '19 at 14:15