C# 为什么这个C代码会产生两次输出
嗨,我是C#的新手,正在测试一个简单的openFileDialog程序。我目前编写的代码似乎正在完成它的工作,但是,输出会生成两次。任何帮助都将不胜感激 我的代码:C# 为什么这个C代码会产生两次输出,c#,visual-studio-2010,C#,Visual Studio 2010,嗨,我是C#的新手,正在测试一个简单的openFileDialog程序。我目前编写的代码似乎正在完成它的工作,但是,输出会生成两次。任何帮助都将不胜感激 我的代码: watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new File
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
MessageBox.Show("copying done");
StreamReader inStream = new StreamReader(destFile);
string line;
string[] lineSplit;
bool errorFound = false;
while ((line = inStream.ReadLine()) != null)
{
lineSplit = line.Split(' ');
for (int i = 0; i < lineSplit.Length; i++)
{
if (lineSplit[i] == textBox2.Text)
{
errorFound = true;
MessageBox.Show("Error found in " + e.Name);
MessageBox.Show("Exiting");
break;
}
}
}
inStream.Close();
}
只是想知道为什么它会打印两次?因为它在
watcher.Created
和watcher.Changed上调用了OnChanged
,您多次附加到同一个处理程序:
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
因此,例如,如果更改的和创建的事件运行,您将获得两次相同的输出
您可能需要为每个事件创建单独的方法。我不知道什么是watcher
,但这里有一个大致的想法:
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
private void OnCreated(object source, FileSystemEventArgs e)
{
// do something when the watcher is created
}
private void OnDeleted(object source, FileSystemEventArgs e)
{
// do something when the watcher is deleted
}
您需要记住的是,单个IO操作可以触发多个不同的FileSystemWatcher
事件
常见文件系统操作可能引发多个事件。例如,当文件从一个目录移动到另一个目录时,可能会引发几个OnChanged事件以及一些OnCreated和OnDeleted事件
最有可能发生的情况是,文件创建同时触发了创建事件和更改事件(我认为windows倾向于创建初始文件(触发创建),然后写入它(触发更改))。但是,这取决于您正在执行的操作。这就是我如何修复它的,不知道这是否是最好的方法,但它确实有效
private static void OnChanged(object source, FileSystemEventArgs e)
{
//set EnableRaisingEvents = false at the start of the method.
FileSystemWatcher t = source as FileSystemWatcher;
t.EnableRaisingEvents = false;
//do stuff that you want in the method, in my case checking for words.
....
....
//Set EnableRaisintEvents true again
t.EnableRaisingEvents = true;
}
这个小补丁确保每次更改只引发一次事件,而不是两次。可能与
private static void OnChanged(object source, FileSystemEventArgs e)
{
//set EnableRaisingEvents = false at the start of the method.
FileSystemWatcher t = source as FileSystemWatcher;
t.EnableRaisingEvents = false;
//do stuff that you want in the method, in my case checking for words.
....
....
//Set EnableRaisintEvents true again
t.EnableRaisingEvents = true;
}