博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Wait until file is closed/unlocked http://blog.lukesw.net/2009/07/wait-until-file-is-closed.html
阅读量:6078 次
发布时间:2019-06-20

本文共 4380 字,大约阅读时间需要 14 分钟。

 

Sometimes you want to wait until some specified file is available for reading/writing. For example, you wait until other process finishes packing into a zip file, or wait until some file is fully uploaded to the server so you can compress it at server side, or something like that. There are some solutions in which checking whether the file can be opened mainly looks like this:

public static bool IsFileAvailable(string path){  try  {    if (!File.Exists(path)) return false;    using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { };    return true;  }  catch (Exception) { return false; }}

There are some drawbacks to this approach. Imagine that this code returns true, but before we actually open the file, some other process or thread manages to open and lock the file. Besides, a generic exception should not be caught, because we might “eat” some really important exception like OutOfMemoryException or similar. A better solution would be to return obtained file stream, and catch only file-related exceptions.

After some refactoring, adding extension methods, and adding ‘wait’ methods, the final code looks like this:

public static class FileExt{  public static FileStream TryOpenFile(string path, FileAccess access, FileShare share)  {    try    {      if (!File.Exists(path)) return null;      return File.Open(path, FileMode.Open, access, share);    }    catch (IOException) { return null; }    catch (UnauthorizedAccessException) { return null; }  }  public static FileStream WaitAndOpenFile(string path, FileAccess access, FileShare share, TimeSpan timeout)  {    DateTime dt = DateTime.UtcNow;    FileStream fs = null;    while ((fs = TryOpenFile(path, access, share)) == null && (DateTime.UtcNow - dt) < timeout)    {      Thread.Sleep(250); // who knows better way and wants a free cookie? ;)    }    return fs;  }#region " Other Methods"  public static FileStream TryOpenFileForReading(this FileInfo fileInfo) { return TryOpenFileForReading(fileInfo.FullName); }  public static FileStream TryOpenFileForReading(string path) { return TryOpenFile(path, FileAccess.Read); }  public static FileStream TryOpenFileForWriting(this FileInfo fileInfo) { return TryOpenFileForWriting(fileInfo.FullName); }  public static FileStream TryOpenFileForWriting(string path) { return TryOpenFile(path, FileAccess.ReadWrite); }  public static FileStream TryOpenFile(this FileInfo fileInfo, FileAccess access) { return TryOpenFile(fileInfo.FullName, access); }  public static FileStream TryOpenFile(string path, FileAccess access) { return TryOpenFile(path, access, FileShare.None); }  public static FileStream TryOpenFile(this FileInfo fileInfo, FileAccess access, FileShare share) { return TryOpenFile(fileInfo.FullName, access, share); }  public static FileStream WaitAndOpenFileForReading(this FileInfo fileInfo, TimeSpan timeout) { return WaitAndOpenFileForReading(fileInfo.FullName, timeout); }  public static FileStream WaitAndOpenFileForReading(string path, TimeSpan timeout) { return WaitAndOpenFile(path, FileAccess.Read, timeout); }  public static FileStream WaitAndOpenFileForWriting(this FileInfo fileInfo, TimeSpan timeout) { return WaitAndOpenFileForWriting(fileInfo.FullName, timeout); }  public static FileStream WaitAndOpenFileForWriting(string path, TimeSpan timeout) { return WaitAndOpenFile(path, FileAccess.ReadWrite, timeout); }  public static FileStream WaitAndOpenFile(this FileInfo fileInfo, FileAccess access, TimeSpan timeout) { return WaitAndOpenFile(fileInfo.FullName, access, timeout); }  public static FileStream WaitAndOpenFile(string path, FileAccess access, TimeSpan timeout) { return WaitAndOpenFile(path, access, FileShare.None, timeout); }  public static FileStream WaitAndOpenFile(this FileInfo fileInfo, FileAccess access, FileShare share, TimeSpan timeout) { return WaitAndOpenFile(fileInfo.FullName, access, share, timeout); }#endregion}

This code also is not perfect. I known of no better method of waiting until a file is closed by the previous owner, except waiting in a loop. We can only make this method a little better by using the Thread.Sleep method which prevents CPU from being used all the time.

There is one more thing. Why is the FileShare.None flag used by default? Only because we do not want other processes/threads to mess with our file which we obtained with such “difficulties”.

转载地址:http://zqqgx.baihongyu.com/

你可能感兴趣的文章
SSPL的MongoDB再被抛弃,GUN Health也合流PostgreSQL
查看>>
微软表示Edge的性能更优于Chrome和Firefox
查看>>
基于容器服务的持续集成与云端交付(三)- 从零搭建持续交付系统
查看>>
Microsoft使用.NET Core SDK遥测数据
查看>>
《Spark GraphX in Action》书评及作者访谈
查看>>
IBM推出了针对区块链部署的云服务
查看>>
关于5G被激烈讨论的那些争端和冲突
查看>>
使用Apache Spark构建实时分析Dashboard
查看>>
2017年InfoQ最受欢迎30项内容清单
查看>>
OpenAI披露最新研究成果:AI训练如何扩展到更大规模?
查看>>
周下载量过200万的npm包被注入恶意代码,Vue、Node项目恐受影响
查看>>
写给Java工程师的面试指南
查看>>
ASP.NET Core 2.1带来SignalR、Razor类库
查看>>
GitHub Desktop发布1.5版本,简化合并冲突解决
查看>>
传奇黑客看衰并行计算:多核处理器纯属浪费
查看>>
linux基础命令介绍十五:推陈出新
查看>>
Linux 内核 4.20 圣诞发布!新增硬件支持,性能有所改进
查看>>
百度云BaaS体系揭秘,突破共识机制、单机计算和串行处理三大瓶颈
查看>>
微服务架构会和分布式单体架构高度重合吗
查看>>
Google 如何设计与构建超大规模的软件系统
查看>>