Question

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();
}
Was it helpful?

Solution

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);
    }
}

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top