【问题标题】:How to deal with rapid consecutive file creation in a folder watched by a FileSystemWatcher?如何处理在 FileSystemWatcher 监视的文件夹中快速连续创建文件?
【发布时间】:2017-02-16 06:35:39
【问题描述】:

我有一个文件夹正在被FileSystemWatcher 的服务监视,我使用这个Answer 来帮助我将大文件写入其中。

但是,如果有大约(100MB 或更多)的连续文件创建,我会遇到问题。

问:我该如何解决这个问题?例如,大约 10 个文件(每个 100MB)写入我的文件夹。

注意:这个文件夹是通过我的网络访问的。可能有文件创建但没有真正完成/完成。 FileSystemWatcher 可以在不完全写入文件的情况下处理文件。

用于检查打开文件是否引发异常的当前代码

private static bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;
        try
        {
            stream = file.Open(FileMode.Open,
                     FileAccess.Read, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

当前代码检查是否创建了文件。

    private void FSWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        var files = getFiles(FSWatcher.Path); //stores all filenames in the directory in a list
        if (files.Count() > 0)
        {
            foreach (string file in files)
            {
                FileInfo file_info = new FileInfo(file);
                while (IsFileLocked(file_info))
                {
                    Thread.Sleep(5000); //Sleep if file unavailable
                }
                //code to process the file
            }
            //some code here
        }
    }

【问题讨论】:

    标签: c# multithreading service .net-3.5 filesystemwatcher


    【解决方案1】:

    我过去处理观看文件夹的方式是使用轮询而不是FileSystemWatcherits not 100% reliable anyway

    我制作的处理器循环遍历每个文件并尝试首先将它们移动到“处理”目录中。只有在文件完成写入后,移动才会(可能*)成功,因此一旦移动成功,移动的线程就可以安全地触发对该文件的处理(例如在新线程中)。请注意,一个文件只能移动一次,这意味着您不会意外地让两个不同的线程同时尝试处理一个文件。

    *:应用程序可以(但很少)创建一个可以在打开时移动的文件

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 2018-11-20
      • 2021-09-14
      相关资源
      最近更新 更多