Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / Visual Basic
Article

How to solve "Cross thread operation not valid"

Rate me:
Please Sign up or sign in to vote.
4.82/5 (86 votes)
7 Oct 2006CPOL1 min read 484.2K   84   77
how to access a control from another thread which didn't create this control.
how to access a control from another thread which didn't create this control.

I faced this issue more than 1 time, I decided to collect info about it and made some changes on the code to simplify this problem to you cause it's really annoying and confusing to work with threading stuff. Here is a small code solves this problem FOREVER and in ANY case.

Error:

<quote> Cross thread operation not valid: Control "XXXXXXXXXX" accessed from a thread other than the thread it was created.

Solution:

1- Create your thread:

Private Strt As System.Threading.Thread


2- Start your thread wherever you want:

Strt = New System.Threading.Thread(AddressOf MyThread1)
Strt.Start()


3- Add the thread sub (MyThread1) and put whatever you want and remember that the lines which access a control from this thread will be separated to into another sub (the Delegate sub)

 Sub MyThread1
       ' Working code
       ' Working code
       ' Working code
       ' Working code
       ' Working code
       ' Working code

       AccessControl()

End Sub


From the previous code you will notice 2 things:
1st: AccessControl the sub which will be delegated.
2nd: ' Working code - which doesn't need a delegate to get it work. In other mean, it doesn't show up the error message you receive.

4- and finally, add the delegated sub:

Private Sub AccessControl()
        If Me.InvokeRequired Then
            Me.Invoke(New MethodInvoker(AddressOf AccessControl)) 
        Else
    ' Code wasn't working in the threading sub
    ' Code wasn't working in the threading sub
    ' Code wasn't working in the threading sub
    ' Code wasn't working in the threading sub
    ' Code wasn't working in the threading sub
            Button2.Visible = True
            Button3.Visible = True
            Opacity = 1
            ShowInTaskbar = True
        End If
    End Sub


From the previous code you will notice that all the codes which wasn't working in the threading sub will be added after "Else" line.
examples for some codes which needs to be delegated:
(Control).Visible
Me.Opacity
Me.ShowInTaskbar

I hope i simplified it enough, and now no worry about this issue again.
Special thanks to jmcilhinney for his help. You can also find this article at this link:
http://www.bitsnips.com/forums/viewtopic.php?p=102#102
Have a nice day :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO InfraDrive
Egypt Egypt
Egyptian freelance programmer and the founder of InfraDrive, Inc.

Check:
https://infradrive.com
https://robomatic.ai
https://robomatic.chat
http://www.tufoxy.com

Comments and Discussions

 
QuestionThank u Pin
ali.hnd28-Oct-17 2:47
ali.hnd28-Oct-17 2:47 
PraiseExcellent solution Pin
Robert Nichols2-Aug-16 8:56
Robert Nichols2-Aug-16 8:56 
GeneralMy vote of 5 Pin
Jeffrey McLellan25-Apr-16 9:33
Jeffrey McLellan25-Apr-16 9:33 
QuestionSimply Clever Idea! Pin
Prabakaran T6-Jul-15 23:10
professionalPrabakaran T6-Jul-15 23:10 
QuestionVery cool! Pin
chris85020-Feb-15 10:14
chris85020-Feb-15 10:14 
QuestionCross-thread operation not valid error Pin
Member 460224719-Jan-15 4:48
Member 460224719-Jan-15 4:48 
QuestionStopping the proccess inside AccessControl Method Pin
Member 1114791718-Dec-14 4:34
Member 1114791718-Dec-14 4:34 
Generalthank u Pin
Member 1116174114-Nov-14 2:22
Member 1116174114-Nov-14 2:22 
Generalyou are awesome!!! Pin
jediYL2-Sep-14 19:07
professionaljediYL2-Sep-14 19:07 
QuestionNo need to use Delagates Pin
Tino Fourie25-Jan-14 23:33
Tino Fourie25-Jan-14 23:33 
Although this article is very old, most of the content is still applicable.

I experienced Cross-thread issues when I implemented the FileSystemWatcher class native to System.IO namespace in stead of the old conventional way of using timers (I did use a timer but found the SystemFileWatcher class beats timers hands down).

The first problem I experience was with a DataGridView. Searches brought me to start using Delegates to update user controls on another thread - needless to say this was way over my head at the time.

Implementing the Delegate process on the DataGridView solved my problem.

The next challenge was to insert an image into a ListView. The first iteration using the Delegate method went flawless BUT failed on the second iteration and the application terminated.

DO NOT implement the following in your code

"System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False"

Sooner or later you will regret this.

However, I kept searching and found the most simple and perfectly stable solution without using Delegates or disabling Cross-Thread checking.

In the Sub where you declare your SystemFileWatcher add the following line of code:
VB
Private Sub StartFileWatcher()

        ' Create a new FileSystemWatcher and set its properties. 
        Dim FileWatcher As New FileSystemWatcher()
        
        FileWatcher.SynchronizingObject = Me

        FileWatcher.Path = txtImageFolder.Text
        
        ' Watch for changes in LastWrite times
        FileWatcher.NotifyFilter = (NotifyFilters.LastAccess)

        ' Add event handlers.
        AddHandler FileWatcher.Changed, AddressOf OnChanged

        ' Begin watching.
        FileWatcher.EnableRaisingEvents = True


    End Sub


FileWatcher.SynchronizingObject = Me allowed me to code as if there was no background thread running.

For more information please refer to this article by Richard Carr:
http://www.blackwasp.co.uk/FileSystemWatcher.aspx[^]

Regards,

Tino
GeneralMy vote of 5 Pin
thams13-Jul-13 8:24
thams13-Jul-13 8:24 
QuestionCross thread Pin
sabuni5-Jan-13 11:05
sabuni5-Jan-13 11:05 
GeneralMy vote of 5 Pin
Disactive16-Dec-12 5:52
Disactive16-Dec-12 5:52 
QuestionNice Article Pin
Satish_Tijare21-Oct-12 19:57
Satish_Tijare21-Oct-12 19:57 
GeneralMy vote of 5 Pin
Osama Al Shammari24-Jul-12 11:30
professionalOsama Al Shammari24-Jul-12 11:30 
GeneralYou Rock! Pin
TimmyTwins3-Jul-12 12:55
TimmyTwins3-Jul-12 12:55 
GeneralRe: You Rock! Pin
JoBrittain6-Jul-12 12:18
JoBrittain6-Jul-12 12:18 
QuestionMy vote Pin
kmf7-Dec-11 23:10
kmf7-Dec-11 23:10 
GeneralMy vote of 5 Pin
Mohammed.Gafoor23-Nov-11 19:55
Mohammed.Gafoor23-Nov-11 19:55 
QuestionAlternative Method Pin
onelopez14-Oct-11 8:24
onelopez14-Oct-11 8:24 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen9-Sep-11 3:19
professionalSunasara Imdadhusen9-Sep-11 3:19 
GeneralMy vote of 5 Pin
Nanda_MR13-Mar-11 23:34
Nanda_MR13-Mar-11 23:34 
GeneralI laughed a lot :) Pin
Member 102216226-Oct-10 23:17
Member 102216226-Oct-10 23:17 
GeneralYou missed the point. Pin
Elagizy27-Oct-10 4:14
Elagizy27-Oct-10 4:14 
GeneralMy vote of 5 Pin
L3CodeProject22-Oct-10 10:47
L3CodeProject22-Oct-10 10:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.