Invalid cross-thread operation: control is from a thread other than the thread that was created on

I am writing a windows filewatcher application that will look for changes in a specified folder and then write the details to a txt file.

I followed closely what is mentioned in this article below http://www.codeproject.com/KB/dotnet/folderwatcher.aspx

When I remove F5 from my application, and then create or modify a file in the folder that is being viewed, it gives the error below.

Please, help

Cross-threading is not valid: the 'txtFolderActivity' control is accessible from a thread other than the thread in which it was created.

+6
file-io
source share
3 answers

You should use the Invoke method in the form, for example. with an anonymous delegate to make changes to the reaction to the event.

An event handler is created using another thread. This 2nd thread cannot access the controls in your form. It must β€œcall” them so that the thread does all the management work that originally created them.

Instead:

myForm.Control1.Text = "newText"; 

you need to write:

 myForm.Invoke(new Action( delegate() { myForm.Control1.Text = "newText"; })); 
+9
source share

You are trying to update the user interface from a thread other than the UI. The UI has thread affinity and can only be updated from the thread that created it. If you use WinForms, check out How to Make Thread-Safe Calls in Windows Forms MSDN Controls . Basically you will need to update the interface through Control.Invoke . For WPF, you need to use DispatcherObject .

+3
source share

Basically, you should have two threads in the application, at least, and the thread your control logic is running in is different, so you get this error because the controls are not thread safe.

This will protect you from problems that can be caused by multiple threads modifying the same control at the same time.

You can find it in much more detail by looking here: http://msdn.microsoft.com/en-us/library/ms171728%28VS.80%29.aspx

+1
source share

All Articles