3

FileSystemWatcher を使用して、システムのフォルダーにファイルが到着するたびに通知します。

時々、それらは (他のプログラムによって) ロックされた状態で到着します。

私は以下のようなことをしたい:

タイムアウト後もロックされている場合はそのファイルを無視するか、タイムアウト中にロックが解除された場合はファイルを処理します

私は現在、この解決策を思いつきましたが、それを達成する他の方法があるかどうか疑問に思っています。

 lockedFilePaths = new List<string>();
 NoLockFilePaths = new List<string>();

 Watcher.Created += (sender, e) => WatcherHandler(e.FullPath);

 WatcherHandler(string FilePath)
 {
     CheckFileAccess(FilePath);
     if (NoLockFilePaths.Any())
     {
          //Process all file paths
     }
 }

 CheckFileAccess(string filepath)
 {
         // start a timer and invoke every say 10ms
         // log the locked time of the file.
         // compare the current time.
         // return null if TIMEOUT exceeds
         // or wait till the TIMEOUT and keep on checking the file access 
 }

問題は、CheckFileAccess をシンプルかつ最適に実装する方法です。

現在、System.Threading.Timer を使用して 1000 ミリ秒ごとに通知し、ファイルがまだロックされているかどうかを確認し、実装が満足できるものではないかどうかを確認します。いくつかの非常に単純な実装の提案を探しています。

4

1 に答える 1

1

同様のことをしなければならないとしたら、次のようにします。

public class Watcher
    {
        public readonly TimeSpan Timeout = TimeSpan.FromMinutes(10);

        private readonly FileSystemWatcher m_SystemWatcher;
        private readonly Queue<FileItem> m_Files;
        private readonly Thread m_Thread;
        private readonly object m_SyncObject = new object();
        public Watcher()
        {
            m_Files = new Queue<FileItem>();
            m_SystemWatcher = new FileSystemWatcher();
            m_SystemWatcher.Created += (sender, e) => WatcherHandler(e.FullPath);
            m_Thread = new Thread(ThreadProc)
                {
                    IsBackground = true
                };
            m_Thread.Start();
        }

        private void WatcherHandler(string fullPath)
        {
            lock (m_SyncObject)
            {
                m_Files.Enqueue(new FileItem(fullPath));
            }
        }

        private void ThreadProc()
        {
         while(true)//cancellation logic needed
         {
            FileItem item = null;
            lock (m_SyncObject)
            {
                if (m_Files.Count > 0)
                {
                    item = m_Files.Dequeue();
                }
            }

            if (item != null)
            {
                CheckAccessAndProcess(item);
            }
            else
            {
                SpinWait.SpinUntil(() => m_Files.Count > 0, 200);
            }
         }
        }

        private void CheckAccessAndProcess(FileItem item)
        {
            if (CheckAccess(item))
            {
                Process(item);
            }
            else
            {
                if (DateTime.Now - item.FirstCheck < Timeout)
                {
                    lock (m_SyncObject)
                    {
                        m_Files.Enqueue(item);
                    }
                }
            }
        }

        private bool CheckAccess(FileItem item)
        {
            if (IsFileLocked(item.Path))
            {
                if (item.FirstCheck == DateTime.MinValue)
                {
                    item.SetFirstCheckDateTime(DateTime.Now);
                }
                return false;
            }

            return true;
        }

        private void Process(FileItem item)
        {
            //Do process stuff
        }

        private bool IsFileLocked(string file)
        {
            FileStream stream = null;
            var fileInfo = new FileInfo(file);

            try
            {
                stream = fileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return false;
        }
    }

    public class FileItem
    {
        public FileItem(string path)
        {
            Path = path;
            FirstCheck = DateTime.MinValue;
        }

        public string Path { get; private set; }
        public DateTime FirstCheck { get; private set; }

        public void SetFirstCheckDateTime(DateTime now)
        {
            FirstCheck = now;
        }
    }

CheckAccess と IsFileLocked から FileStream オブジェクトを返して、CheckAccess と Process の呼び出しの間に別のプロセスからファイル ハンドルが取得されないようにすることができます。

于 2013-08-05T11:54:05.580 に答える