简体   繁体   English

锁定AppendAllText与TextWriter

[英]Locking AppendAllText vs TextWriter

Regarding the preventing of "already in use" errors i want to ask if the first code snippet could potentialy be dangerous if called multiple times from multiple clients? 关于防止“已使用”错误,我想问一下如果从多个客户端多次调用第一个代码段是否可能存在危险? Or are both code blocks equaly safe ? 还是两个代码块都一样安全?

I am asking because the second codesnippet calls a close method which also does a dispose which sounds safer. 我问是因为第二个代码片段调用了close方法,该方法也做一个听起来更安全的处置。

//FIRST
lock (_myLock)
{
    File.AppendAllText(_filePath, text);
}


//SECOND
lock (_myLock)
{
    TextWriter tw = new StreamWriter(_filePath, true);
    tw.Write(text);
    tw.Close();
}

They are both the same. 他们都是一样的。 File.AppendAllText calls Dispose too. File.AppendAllText调用也进行Dispose。

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

Both are equally Safe. 两者同样安全。

As you have applied the Lock so even if it is called from multiple clients only one thread will be executing at a particular time so it is not dangerous rather first option is more simple 由于您已经应用了Lock,因此即使从多个客户端调用了Lock,在特定的时间也只会执行一个线程,因此这并不危险,第一种选择更简单

As MSDN says about AppendAllText method 正如MSDN所说的关于AppendAllText方法

The file handle is guaranteed to be closed by this method

So in the first piece of code .Net is already doing the extra work your are doing in approach 2 因此,在第一段代码中,.Net已经在做方法2中要做的额外工作

I think what you are doing in latter is already taken care internally when called File.AppendAllText 我认为您在后者中执行的操作在调用File.AppendAllText时已经在内部进行了处理

the same is answered here File.AppendAllText vs StreamWriter 同样的答案在这里File.AppendAllText vs StreamWriter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM