Developer Logs

Every once in awhile I hit a (technical) wall, stumble upon a great tool or look for a reason to improve 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
            // Append text to the file
            using (StreamWriter sw = File.AppendText(path))
            // Release lock

Any questions? Feel free to comment or connect!

comments powered by Disqus