Skip to main content

When a previous Thread isn't done writing to a file, and the other Thread starts writing, you can get an exception similar to, "The process cannot access the file path because it is being used by another process." You need the the thread to 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).

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

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