I don't get this --> Make Thread-Safe Calls to Windows Forms Controls

L

ljh

I am trying to run some pretty simple code that monitors a folder for
changes (copied the example at
http://www.codeproject.com/dotnet/folderwatcher.asp).

But, when I try and update a textbox control I keep getting the
"Cross-thread operation not valid: Control 'txt_folderactivity' accessed
from a thread other than the thread it was created on." error.

I found the Microsoft explanation at
http://msdn2.microsoft.com/en-us/library/ms171728(VS.80,d=ide).aspx, but I
just don't get the explanation.

Can somebody help me understand why I can't simply set the text property
from a thread and what this Microsoft explanation is trying to tell me?

Thanks!
 
H

Herfried K. Wagner [MVP]

ljh said:
I am trying to run some pretty simple code that monitors a folder for
changes (copied the example at
http://www.codeproject.com/dotnet/folderwatcher.asp).

But, when I try and update a textbox control I keep getting the
"Cross-thread operation not valid: Control 'txt_folderactivity' accessed
from a thread other than the thread it was created on." error.

Set the filesystemwatcher's 'SynchronizingObject' property to the textbox.
 
B

Brian Gideon

Windows forms and controls can only be accessed from the thread they
were created on. That is the main UI thread. The FileSystemWatcher
events come from some other thread. The cross-thread operation error
you see is coming from a Managed Debugging Assistant (MDA) which is
nice enough to warn you of the potential problem in debug builds. MDAs
are not compiled into release builds. They are a new feature in 2.0.

Setting the SynchronizingObject property to a Form or Control in your
application tells the FileSystemWatcher to automatically marshal the
execution of events onto the thread that created that form or control.
 
L

ljh

Thanks for the explanation....

Now I am finding out all of the GOTCHAs associated with using the
FileSystemWatcher control (see the
"FileSystemWatcher raises Changed Twice...." thread for all of the gory
details).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top