Her*_*art 1 c# locking file process textwriter
关于防止"已经使用"错误,我想问一下,如果多个客户端多次调用第一个代码片段可能会有危险吗?或者两个代码块是否安全?
我问,因为第二个codenippet调用了一个close方法,该方法也进行了一个听起来更安全的配置.
//FIRST
lock (_myLock)
{
File.AppendAllText(_filePath, text);
}
//SECOND
lock (_myLock)
{
TextWriter tw = new StreamWriter(_filePath, true);
tw.Write(text);
tw.Close();
}
Run Code Online (Sandbox Code Playgroud)
它们都是一样的.File.AppendAllText呼叫也处理.
private static void InternalAppendAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter writer = new StreamWriter(path, true, encoding))
{
writer.Write(contents);
}
}
Run Code Online (Sandbox Code Playgroud)