【问题标题】:how to wait for filesystemwatcher event to finish如何等待 filesystemwatcher 事件完成
【发布时间】:2013-01-29 00:09:58
【问题描述】:

如果这是多余的,请原谅,但是与此相关的所有问题似乎都指向不同的方向,而且我是多线程编程的新手。

我的代码中有一个FileSystemWatcher 类,它监视创建的事件。看起来文件系统观察程序的创建事件启动了它自己的线程。因此,有时调用线程会在FileSystemWatcher created 事件的被调用线程中启动的工作完成之前继续它的工作。我不想要这个。我的工作流程需要是单线程的,所以我想要实现的是在调用线程有机会恢复之前等待创建的事件完成它的工作。

伪代码:

main() {
FileSystemWatcher fsw = new FileSystemWatcher()
fsw.Path = ini.location;
fsw.Created += new FileSystemEventHandler(OnFileCreation);
fsw.EnableRaisingEvents = true;
main_engine.processDataToFile();
main_engine.processCreatedFile();
}

void OnFileCreation(object sender, FileSystemEventArgs e) {
// do some file processing
// takes time based on size of file and whether file is locked or not etc.
}

void processDataToFile() {
// do some data processing on received data and output to a file. 
}

void processCreatedFile() {
// do not want this method to be called, unless OnFileCreation() finish it's work.
}

选择使用FileSystemWatcher 的原因是因为有时会直接放置文件进行处理,而不是 main_engine 先获取数据并且它可以在多个位置工作,所以不想在FileSystemWatcher 可用时推出本土解决方案.

【问题讨论】:

  • 你想监控什么事件..看看FileSystemWatcher Class这里
  • @DJKRAZE:OP 说“已创建”。
  • watcher.Created += new FileSystemEventHandler(OnChanged); 这是我发布的链接的一部分......所以罗伯特哈维不确定你在说什么......
  • @DJKRAZE:他正在尝试监控 Created 事件。

标签: c# multithreading filesystemwatcher


【解决方案1】:

如果事件在单独的线程中触发,则不能使其成为单线程。因为这不是你的代码。故事结束。

但是等待很简单:

...
    me.WaitOne();
    main_engine.processCreatedFile();
}

...

void OnFileCreation(object sender, FileSystemEventArgs e) {
// do some file processing
// takes time based on size of file and whether file is locked or not etc.
...
me.Set();
}

ManualResetEventSlim me = new ManualResetEventSlim(false);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多