【问题标题】:Does FileShare.ReadWrite imply thread-safe writing to a file in C#FileShare.ReadWrite 是否暗示线程安全写入 C# 中的文件
【发布时间】:2014-09-24 16:19:24
【问题描述】:
using (FileStream fs =  File.Open(@"C:\logs\log1.txt",FileMode.Append,
              FileAccess.Write, FileShare.ReadWrite))
{

    using (StreamWriter w = new StreamWriter(fs))
    {
        w.WriteLine(logMessage);
        w.Flush();
        isSuccessful = true;
    }
} 

在上面的代码中,我正在实例化一个 FileStream 对象,因此文件以 FileShare.ReadWrite 模式打开。

我的问题:这是否意味着向打开的文件中写入一行的代码将是线程安全的,或者 FileShare.ReadWrite 意味着线程安全之外的其他内容?

【问题讨论】:

    标签: c# multithreading filestream


    【解决方案1】:

    不,它只允许多个进程写入文件。如果你希望它是线程安全的,你仍然需要在 File.Write 操作上实现一些锁定机制。

    查看此问题的答案以获取更多信息:What is the fastest and safest way to append records to disk file in highly loaded .ashx http handler?

    【讨论】:

      【解决方案2】:

      FileShare 与线程安全无关。 FileAccessFileShare 的值仅在打开文件时使用。他们可能会导致失败,并且他们控制着您和其他人拥有的权利。

      除此之外,当涉及多个进程和线程时,行为不会发生变化。

      单个FileStream 实例不是线程安全的。

      【讨论】:

        猜你喜欢
        • 2020-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        • 2012-04-26
        • 1970-01-01
        相关资源
        最近更新 更多