File.WriteAllText和并发访问 [英] File.WriteAllText and Concurrent Accesses

查看:1995
本文介绍了File.WriteAllText和并发访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在写一个很长的字符串使用File.WriteAllText一个文件,而另一个线程或进程正在尝试读取相同的文件。难道抛出任何异常?换句话说,什么是文件共享参数的File.WriteAllText方法使用?这不是写在文件中!

Suppose I'm writing a very long string to a file using File.WriteAllText, and another thread or process is trying to read the same file. Would it throw any exception? In other words, what is the FileShare parameter that the File.WriteAllText method uses? It's not written in the documentation!

推荐答案

这是源代码的.NET Framework 4.0。明确的StreamWriter是用来使用FileShare.Read内部。

This is the source code from .net Framework 4.0. clearly StreamWriter is used that Uses FileShare.Read Internally.

    [SecuritySafeCritical]
public static void WriteAllText(string path, string contents)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM);
}


private static void InternalWriteAllText(string path, string contents, Encoding encoding)
{
    using (StreamWriter writer = new StreamWriter(path, false, encoding))
    {
        writer.Write(contents);
    }
}

这是创建的StreamWriter底层流的代码

This is the code that creates the underlying stream for StreamWriter.

private static Stream CreateFile(string path, bool append)
{
    return new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000, FileOptions.SequentialScan);
}

这篇关于File.WriteAllText和并发访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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