FileShare.None是否使线程等待文件流关闭? [英] Does FileShare.None make threads wait until the filestream is closed?

查看:133
本文介绍了FileShare.None是否使线程等待文件流关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用文件流时,将FileShare设置为None,并说两个同时访问同一功能的用户想要对该文件进行读/写. FileShare.None是让第二个用户请求等待还是第二个用户的请求抛出异常?

When using a file stream, and setting FileShare to None, and say two users accessing the same function at the same time want to read/write to that file. Will FileShare.None make the second users request waiting or will the second user's request throw an 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说:无拒绝共享当前文件.在打开文件之前,任何通过该过程或其他过程打开文件的请求都将失败.

但是请求会一直尝试直到关闭文件流吗?

But will requests keep trying until the filestream is closed?

推荐答案

当某个进程选择使用FileShare.None对文件进行读/写操作时,任何随后对该文件进行的任何访问都将导致Acess Denied Exception.要回答您的问题,第二个用户将获得例外.

When a process opean a file for Read/Write with FileShare.None any subsequent access by any process on this same file will result in Acess Denied Exception. To answer your question, Second user will get exception.

MSDN :FileShare.None-拒绝共享当前文件.任何要求打开 文件(通过此过程或其他过程)将失败,直到该文件被 关闭.

MSDN: FileShare.None - Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.


您可以通过多种方式处理此类并发文件访问问题,以下代码演示了一种解决这种情况的简单方法.


There are many ways you can handle these kind of concurrent file access issues, Following code demonstrates a simple approach to tackle this situation.

//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);
    }
}

这篇关于FileShare.None是否使线程等待文件流关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆