Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
468 views
Welcome To Ask or Share your Answers For Others

1 Answer

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";
}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...