tags:

views:

842

answers:

3

Hello, I am writing a filewatcher windows application which will look for changes in a specified folder and then logs the details in a txt file.

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

When I hit F5 from my application and then create or modify a file in the folder that is being watched it throws the below mentioned error.

Please help

Cross-thread operation not valid: Control 'txtFolderActivity' accessed from a thread other than the thread it was created on.

+3  A: 

You have to use the Invoke method on the form e.g. with an anonymous delegate to make your changes in reaction to the event.

The event handler is raised with another thread. This 2nd thread cannot access controls in your form. It has to "Invoke" them to let the thread do all control work that initially created them.

Instead of:

myForm.Control1.Text = "newText";

you have to write:

myForm.Invoke(new Action(
delegate()
{
  myForm.Control1.Text = "newText";
}));
Mischa
+1 - I need to try your way to solve this problem, as it is considerably simpler than my current approach.
James Black
+1 Thanks a lot @Mischa. It made my task very easy. :)
Ismail
A: 

You are trying to update the UI from a non-UI thread. UI has a thread affinity and can only be updated from a thread that created it. If you're using WinForms, check out How to: make thread-safe calls to Windows Forms Controls MSDN article. Basically you will need to update the UI via Control.Invoke method. For WPF, you need to use DispatcherObject.

Mehmet Aras
A: 

Basically you must have two threads in your application, at least, and the thread that your control logic is on is different, so you get this error, as the controls are not threadsafe.

This is to protect you from problems that could be caused by multiple threads changing the same control at the same time.

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

James Black