---
title: "How do you write a log file in a thread-safe way?"  
description: "How do you write a log file in a thread-safe way?"  
author: "ICSM Computer"  
published: 2025-05-08  
updated: 2025-06-01  
canonical: https://www.mindstick.com/forum/161594/how-do-you-write-a-log-file-in-a-thread-safe-way  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 2 minutes  

---

# How do you write a log file in a thread-safe way?

How do you write a [log file](https://www.mindstick.com/articles/327201/create-log-file-in-c-sharp) in a thread-[safe](https://www.mindstick.com/articles/126322/how-to-keep-your-home-safe-while-traveling) way?

## Replies

### Reply by ICSM Computer

To write a **[log](https://www.mindstick.com/articles/126269/the-main-uses-of-log-cabins) [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) 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

```cs
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:

```plaintext
ThreadSafeLogger.Log("User logged in");
```

1. The `lock` ensures only one thread writes at a time.
2. `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:

```cs
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:

```cs
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 |


---

Original Source: https://www.mindstick.com/forum/161594/how-do-you-write-a-log-file-in-a-thread-safe-way

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
