1

关于防止“已在使用”错误,我想问一下,如果从多个客户端多次调用,第一个代码片段是否可能是危险的?还是两个代码块都同样安全?

我之所以问,是因为第二个代码片段调用了一个 close 方法,该方法也执行了一个听起来更安全的处置。

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


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

3 回答 3

5

他们都是一样的。File.AppendAllText也调用 Dispose。

private static void InternalAppendAllText(string path, string contents, Encoding encoding)
{
    using (StreamWriter writer = new StreamWriter(path, true, encoding))
    {
        writer.Write(contents);
    }
}
于 2012-01-03T09:27:53.310 回答
1

两者都同样安全。

由于您已经应用了锁,因此即使从多个客户端调用它,也只有一个线程会在特定时间执行,所以这并不危险,而是第一个选项更简单

正如 MSDN 所说的AppendAllText方法

The file handle is guaranteed to be closed by this method

因此,在第一段代码中,.Net 已经在完成您在方法 2 中所做的额外工作

于 2012-01-03T09:26:30.377 回答
1

我认为您在后者中所做的事情在调用 File.AppendAllText 时已经在内部得到了照顾

同样的答案在这里File.AppendAllText vs StreamWriter

于 2012-01-03T09:31:43.637 回答