Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# FileShare.None是否使线程等待文件流关闭?_C#_.net_File_Thread Safety_Fileshare - Fatal编程技术网

C# FileShare.None是否使线程等待文件流关闭?

C# FileShare.None是否使线程等待文件流关闭?,c#,.net,file,thread-safety,fileshare,C#,.net,File,Thread Safety,Fileshare,使用文件流时,将FileShare设置为None,并假设两个同时访问同一功能的用户想要读/写该文件。FileShare.None是否会让第二个用户的请求等待,或者第二个用户的请求是否会引发异常 //two users get to this this code at the same time using (FileStream filestream = new FileStream(chosenFile, FileMode.OpenOrCreate, FileAccess.ReadWrite

使用文件流时,将
FileShare
设置为
None
,并假设两个同时访问同一功能的用户想要读/写该文件。
FileShare.None
是否会让第二个用户的请求等待,或者第二个用户的请求是否会引发异常

//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对文件进行读/写操作时。无
任何进程对同一文件的后续访问都将导致
拒绝访问异常。要回答您的问题,第二个用户将获得异常

: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=-2147024864
Message=进程无法访问文件“路径”,因为它正被另一个进程使用。

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

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

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

由于OP指的是线程,值得指出的是,错误消息不一定正确。无论哪个进程锁定了文件,您都会收到相同的错误消息,即使该进程与试图打开文件的进程相同,您也会收到相同的错误消息。您是否可以在文件流的情况下编写此代码实例,如我所问的问题?@dotctor该文件将由两个不同的.net页面在两个不同的函数中访问。很抱歉,我刚才没有提到那件事。看起来kurubaran解决方案是我最好的选择。这个解决方案在某种程度上会起作用。但我还是最好使用监视器/锁,它会抛出
IOException