Developer Logs

Every once in awhile I hit a (technical) wall, stumble upon a great tool or look for a reason to increase my English.
This is my place to share, welcome to my logs.

Thread Safe File Writing in C# (Wait On Lock)

I've been working on a Twitter Streaming search application that uses extensive logging. To memory and text files, now I use Multi Threading for this to work properly. At some point I started getting exceptions, the logging file is allready in use:

The process cannot access the file '{path}' because it is being used by another process

Well this is expected, the previous Thread isn't done writing to the file while the other Thread starts writing. They should wait in line and write when the previous write action is completed. Well, you could write the code yourself or use the ReaderWriterLockSlim Class (reference: MSDN).

With the following result:

public class Demo {
    private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();

    public void WriteToFileThreadSafe(string text, string path) {
        // Set Status to Locked
        _readWriteLock.EnterWriteLock();
        try
        {
            // Append text to the file
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine(text);
                sw.Close();
            }
        }
        finally
        {
            // Release lock
            _readWriteLock.ExitWriteLock();
        }
    }
}

Any questions? Feel free to comment or connect!

Picture of Johan Dorper
I'm Johan a .NET Developer (prefer C#) / ScrumMaster from Nunspeet, The Netherlands.
Feel free to mention me on Twitter or drop an e-mail.
comments powered by Disqus