FileShare.None是否让线程等到文件流关闭?

使用文件流时,将FileShare设置为None ,并说两个用户同时访问同一个函数想要读/写该文件。 FileShare.None会让第二个用户请求等待还是第二个用户的请求会抛出exception?

 //two users get to this this code at the same time using (FileStream filestream = new FileStream(chosenFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) using (StreamReader sr = new StreamReader(filestream)) using (StreamWriter sw = new StreamWriter(filestream)) { //reading and writing to file } 

Msdn说:无拒绝共享当前文件。 在文件关闭之前,任何打开文件的请求(通过此进程或其他进程)都将失败。

但请求会继续尝试,直到文件流关闭?

当进程使用FileShare.None打开读/写文件时,任何进程对此同一文件的任何后续访问都将导致Acess Denied Exception 。 要回答您的问题,第二位用户将获得例外。

MSDN :FileShare.None – 拒绝共享当前文件。 在文件关闭之前,任何打开文件的请求(通过此进程或其他进程)都将失败。


有许多方法可以处理这些并发文件访问问题,下面的代码演示了一种解决这种情况的简单方法。

 //Retry 5 times when file access fails int retryCounter = 5; while (!isFileAccessSuccess && retryCounter > 0) { try { //Put file access logic here //If the file has been accessed successfully set the flag to true isFileAccessSuccess = true; } catch (Exception exception) { //Log exception } finally { //Decrease the retry count --retryCounter; } if (!isFileAccessSuccess) { //Wait sometime until initiating next try Thread.Sleep(10000); } } 

不, IOException将被抛出一个HResult = -2147024864Message = The process cannot access the file 'path' because it is being used by another process.

如果要同步对文件的访问权限,可以使用命名等待句柄。

 public class FileAcessSynchronizer { private readonly string _path; private readonly EventWaitHandle _waitHandle; public FileAcessSynch(string path) { _path = path; _waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, "NameOfTheWaitHandle"); } public void DoSomething() { try { _waitHandle.WaitOne(); using (FileStream filestream = new FileStream(chosenFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) using (StreamReader sr = new StreamReader(filestream)) using (StreamWriter sw = new StreamWriter(filestream)) { //reading and writing to file } } finally { _waitHandle.Set(); } } } 

由于命名等待句柄创建了一个关键部分 ,因此应用程序的两个线程或进程(使用与等待句柄名称相同的名称)可以同时执行其中的代码。 因此,一个线程或进程进入该部分,以没有人可以访问它的方式打开文件(其他应用程序),执行命令,最后离开临界区以允许应用程序的其他线程或进程进入关键部分。