Reputation: 1729
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.
//FIRST
lock (_myLock)
{
File.AppendAllText(_filePath, text);
}
//SECOND
lock (_myLock)
{
TextWriter tw = new StreamWriter(_filePath, true);
tw.Write(text);
tw.Close();
}
Upvotes: 1
Views: 2791
Reputation: 59
I think what you are doing in latter is already taken care internally when called File.AppendAllText
the same is answered here File.AppendAllText vs StreamWriter
Upvotes: 1
Reputation: 12366
They are both the same. File.AppendAllText
calls Dispose too.
private static void InternalAppendAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter writer = new StreamWriter(path, true, encoding))
{
writer.Write(contents);
}
}
Upvotes: 5
Reputation: 30117
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
As MSDN says about AppendAllText
method
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
Upvotes: 1