Click here to Skip to main content
12,826,151 members (30,499 online)
Click here to Skip to main content
Add your own
alternative version

Stats

350.8K views
84 bookmarked
Posted 7 Oct 2006

How to solve "Cross thread operation not valid"

, 7 Oct 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
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.</quote />

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)

Share

About the Author

Elagizy
Software Developer (Senior) InfraDrive
Egypt Egypt
Egyptian freelance programmer and the founder of InfraDrive, Inc.

Check:
http://www.infradrive.com
http://www.tufoxy.com
http://www.bitsnips.com

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionwriting all the code in access control? [modified] Pin
Hari Om Prakash Sharma24-Jun-07 20:14
memberHari Om Prakash Sharma24-Jun-07 20:14 
AnswerRe: writing all the code in access control? Pin
elagizy24-Jun-07 21:57
memberelagizy24-Jun-07 21:57 
GeneralThanks again Pin
Elrond15-Jun-07 1:20
memberElrond15-Jun-07 1:20 
GeneralOutstanding! Pin
Fabio Videira8-Jun-07 11:10
memberFabio Videira8-Jun-07 11:10 
GeneralIt simply works :-) Pin
Diego F.24-May-07 5:58
memberDiego F.24-May-07 5:58 
Generalcross thread operation Pin
evergreen50115-May-07 5:07
memberevergreen50115-May-07 5:07 
Generalthis is easy yet brilliant Pin
sunlight2-May-07 18:46
membersunlight2-May-07 18:46 
QuestionPlease excuse my ignorance... Pin
HD-P26-Apr-07 11:38
memberHD-P26-Apr-07 11:38 
I cannot seems to apply your solution to a little program I was looking at...
I would appreciate any help in this matter. I saw the "Dirty Fix", which worked, but I would rather know what I was really doing wrong.

The errors occur in the "Private Sub logchange" and "Private Sub logrename"

I am VERY new to the .NET world... Thanks again...

Imports System.IO
Imports System.Diagnostics

Public Class Form1
Inherits Form

Public watchfolder As FileSystemWatcher

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub btn_startwatch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_startwatch.Click
watchfolder = New System.IO.FileSystemWatcher()

'this is the path we want to monitor
watchfolder.Path = Txt_watchpath.Text

'Add a list of Filter we want to specify
'make sure you use OR for each Filter as we need to
'all of those

watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes

' add the handler to each event
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange

' add the rename handler as the signature is different
AddHandler watchfolder.Renamed, AddressOf logrename

'Set this property to true to start watching
watchfolder.EnableRaisingEvents = True

btn_startwatch.Enabled = False
btn_stop.Enabled = True

'End of code for btn_start_click


End Sub

Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
'The following stops the Cross-Tread operation not valid - Error
'System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False

If e.ChangeType = IO.WatcherChangeTypes.Changed Then
txt_folderactivity.Text &= "File " & e.FullPath & _
" has been modified" & vbCrLf
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
txt_folderactivity.Text &= "File " & e.FullPath & _
" has been created" & vbCrLf
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
txt_folderactivity.Text &= "File " & e.FullPath & _
" has been deleted" & vbCrLf
End If

'Reverse "Check for Illegal Cross Thread"
'System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = True

End Sub

Private Sub logrename(ByVal source As Object, ByVal e As _
System.IO.RenamedEventArgs)
'The following stops the Cross-Tread operation not valid - Error
'System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False

txt_folderactivity.Text &= "File " & e.OldName & _
" has been renamed to " & e.Name & vbCrLf
'Reverse "Check for Illegal Cross Thread"
'System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = True
End Sub

Private Sub btn_stop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_stop.Click
' Stop watching the folder
watchfolder.EnableRaisingEvents = False
btn_startwatch.Enabled = True
btn_stop.Enabled = False

End Sub
End Class





GeneralAny Solution for Same In .net 3.0 Pin
sumit_4palz25-Apr-07 0:04
membersumit_4palz25-Apr-07 0:04 
GeneralRe: Any Solution for Same In .net 3.0 Pin
elagizy25-Apr-07 4:00
memberelagizy25-Apr-07 4:00 
AnswerRe: Any Solution for Same In .net 3.0 Pin
MaxtorM1236-Nov-08 6:50
memberMaxtorM1236-Nov-08 6:50 
QuestionHOW TO SOLVE: "Cross thread operation not valid" (DIRTY WAY) Pin
Miroslav Stampar12-Apr-07 5:16
memberMiroslav Stampar12-Apr-07 5:16 
GeneralClear, concise and works perfectly! Pin
VorTechS11-Apr-07 22:21
memberVorTechS11-Apr-07 22:21 
GeneralThx Pin
todwag4-Apr-07 5:27
membertodwag4-Apr-07 5:27 
GeneralWelcome all Pin
elagizy17-Mar-07 22:08
memberelagizy17-Mar-07 22:08 
GeneralThanks a lot! Pin
Raymond S.K.17-Mar-07 19:27
memberRaymond S.K.17-Mar-07 19:27 
GeneralThanks Pin
LOKIN SHAH5-Mar-07 16:35
memberLOKIN SHAH5-Mar-07 16:35 
GeneralThanks! Pin
Member #229774215-Feb-07 9:52
memberMember #229774215-Feb-07 9:52 
GeneralThanks!!! Pin
Member #25547358-Feb-07 16:52
memberMember #25547358-Feb-07 16:52 
GeneralThx - this solution rocks Pin
Andy3231-Jan-07 12:55
memberAndy3231-Jan-07 12:55 
GeneralVery nice Pin
todd200011-Jan-07 7:01
membertodd200011-Jan-07 7:01 
GeneralWorks in C# too [modified] Pin
iamstarbuck10-Dec-06 23:22
memberiamstarbuck10-Dec-06 23:22 
GeneralOMG, thank you so much Pin
Vinc__426-Oct-06 6:51
memberVinc__426-Oct-06 6:51 
GeneralThnaks Pin
UnRusoDeCaracas25-Oct-06 10:36
memberUnRusoDeCaracas25-Oct-06 10:36 
GeneralHi Pin
Marco225020-Oct-06 13:45
memberMarco225020-Oct-06 13:45 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 7 Oct 2006
Article Copyright 2006 by Elagizy
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid