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

本文关键字:超时 文件锁 释放 多线程 上下文 监视 | 更新日期: 2023-09-27 18:18:45

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

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

如果我必须做类似的事情,我会这样做:

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和isfilellocked中,你可以返回FileStream对象,以确保在CheckAccess和process调用之间不会从另一个进程获得文件句柄;