To write a logfile in a thread-safe way in C#, you need to ensure that
multiple threads don't write to the file simultaneously, which can cause corruption or data loss.
Recommended Approach: Use lock for Thread Safety
Example: Basic Thread-Safe Logger
using System;
using System.IO;
using System.Threading;
public static class ThreadSafeLogger
{
private static readonly object _lock = new object();
private static readonly string _logFilePath = "log.txt";
public static void Log(string message)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} - {message}";
lock (_lock)
{
File.AppendAllText(_logFilePath, logEntry + Environment.NewLine);
}
}
}
Usage:
ThreadSafeLogger.Log("User logged in");
The lock ensures only one thread writes at a time.
AppendAllText is used to append without overwriting the file.
Alternative: Use StreamWriter with lock
If you're doing frequent logging, reusing a StreamWriter is more efficient:
public class ThreadSafeStreamLogger : IDisposable
{
private readonly StreamWriter _writer;
private readonly object _lock = new object();
public ThreadSafeStreamLogger(string path)
{
_writer = new StreamWriter(path, append: true)
{
AutoFlush = true
};
}
public void Log(string message)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} - {message}";
lock (_lock)
{
_writer.WriteLine(logEntry);
}
}
public void Dispose()
{
_writer.Dispose();
}
}
Usage:
var logger = new ThreadSafeStreamLogger("app.log");
logger.Log("App started");
Dispose when done (or use with a using block).
High-Performance Option: Use ConcurrentQueue + Background Writer
For high throughput or async apps, log to a queue and let a background thread write to the file.
Let me know if you'd like a full example of that pattern.
Summary
Technique
Thread-Safe
Suitable For
lock + File.AppendAllText
Yes
Low-frequency logging
lock + shared StreamWriter
Yes
Frequent logging
ConcurrentQueue + worker thread
Yes
High-performance logging
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
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 write a log file in a thread-safe way in C#, you need to ensure that multiple threads don't write to the file simultaneously, which can cause corruption or data loss.
Recommended Approach: Use
lockfor Thread SafetyExample: Basic Thread-Safe Logger
Usage:
lockensures only one thread writes at a time.AppendAllTextis used to append without overwriting the file.Alternative: Use
StreamWriterwithlockIf you're doing frequent logging, reusing a
StreamWriteris more efficient:Usage:
Dispose when done (or use with a
usingblock).High-Performance Option: Use
ConcurrentQueue+ Background WriterFor high throughput or async apps, log to a queue and let a background thread write to the file.
Let me know if you'd like a full example of that pattern.
Summary
lock+File.AppendAllTextlock+ sharedStreamWriterConcurrentQueue+ worker thread