To ensure thread-safe access when multiple threads write to the
same file in C#, you must synchronize access to prevent race conditions, data corruption, or file lock exceptions.
Here are several approaches:
1. Use a lock for synchronization
Ensure only one thread writes at a time:
private static readonly object fileLock = new object();
public static void WriteToFile(string path, string text)
{
lock (fileLock)
{
File.AppendAllText(path, text + Environment.NewLine);
}
}
2. Use ConcurrentQueue with a background writer thread
This pattern allows threads to enqueue write requests, and a single thread handles the file writes.
private static readonly ConcurrentQueue<string> logQueue = new ConcurrentQueue<string>();
private static readonly AutoResetEvent logSignal = new AutoResetEvent(false);
private static readonly string logFilePath = "log.txt";
public static void StartLogger()
{
Task.Run(() =>
{
while (true)
{
logSignal.WaitOne(); // Wait for signal
while (logQueue.TryDequeue(out string? line))
{
File.AppendAllText(logFilePath, line + Environment.NewLine);
}
}
});
}
public static void Log(string message)
{
logQueue.Enqueue(message);
logSignal.Set(); // Signal the logger
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To ensure thread-safe access when multiple threads write to the same file in C#, you must synchronize access to prevent race conditions, data corruption, or file lock exceptions.
Here are several approaches:
1. Use a
lockfor synchronizationEnsure only one thread writes at a time:
2. Use
ConcurrentQueuewith a background writer threadThis pattern allows threads to enqueue write requests, and a single thread handles the file writes.
3. Use
SemaphoreSlimfor async scenariosWhat to avoid: