Skip to content

Instantly share code, notes, and snippets.

@Doggie52
Created August 16, 2018 13:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Doggie52/d1df64c029f029cf21b1f7d6c88aff1f to your computer and use it in GitHub Desktop.
Save Doggie52/d1df64c029f029cf21b1f7d6c88aff1f to your computer and use it in GitHub Desktop.
Thread-safely write to files in C#
using System.IO;
using System.Threading;
namespace Util
{
/// <summary>
/// Various extensions to the String class.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Writes to a file in a thread-safe manner using a Mutex lock.
/// Overwrites files by default.
/// </summary>
/// <remarks>Inspired by https://stackoverflow.com/a/229567 .</remarks>
/// <param name="output">Input string to write to the file.</param>
/// <param name="filePath">Path of file to write to.</param>
/// <param name="overwrite">Whether to overwrite pre-existing files.</param>
public static void SafelyWriteToFile( this string output, string filePath, bool overwrite = true )
{
// Unique id for global mutex - Global prefix means it is global to the machine
// We use filePath to ensure the mutex is only held for the particular file
string mutexId = string.Format( "Global\\{{{0}}}", Path.GetFileNameWithoutExtension( filePath ) );
// We create/query the Mutex
using ( var mutex = new Mutex( false, mutexId ) ) {
var hasHandle = false;
try {
// We wait for lock to release
hasHandle = mutex.WaitOne( Timeout.Infinite, false );
// Write to file
if ( overwrite )
File.WriteAllText( filePath, output );
else
File.AppendAllText( filePath, output );
} finally {
// If we have the Mutex, we release it
if ( hasHandle )
mutex.ReleaseMutex();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment