监视多线程上下文中超时的文件锁定释放

时间:2013-06-18 05:22:30

标签: c# multithreading .net-4.0 .net-4.5

我正在使用FileSystemWatcher在文件到达系统文件夹时通知我。

有时,他们带锁(通过其他程序)

我想执行以下内容:

如果它们在TIMEOUT之后仍然被锁定,我们会忽略该文件 或者如果它们在TIMEOUT中变为无锁,我们处理文件

我目前想出了这个解决方案,但想知道是否还有其他方法可以实现它。

 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毫秒通知我一次,检查文件是否仍然被锁定,我的实现对我来说不满意。寻找一些超级简单实现的建议。

1 个答案:

答案 0 :(得分: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调用之间的另一个进程获取文件句柄;