Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

file io - Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...