---
title: "How do you ensure thread-safe access when multiple threads are writing to the same file?"  
description: "How do you ensure thread-safe access when multiple threads are writing to the same file?"  
author: "ICSM Computer"  
published: 2025-05-11  
updated: 2025-05-11  
canonical: https://www.mindstick.com/interview/34102/how-do-you-ensure-thread-safe-access-when-multiple-threads-are-writing-to-the-same-file  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 3 minutes  

---

# How do you ensure thread-safe access when multiple threads are writing to the same file?

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:

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

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

### 3. Use `SemaphoreSlim` for async scenarios

```cs
private static readonly SemaphoreSlim fileSemaphore = new SemaphoreSlim(1, 1);

public static async Task WriteToFileAsync(string path, string text)
{
    await fileSemaphore.WaitAsync();
    try
    {
        await File.AppendAllTextAsync(path, text + Environment.NewLine);
    }
    finally
    {
        fileSemaphore.Release();
    }
}
```

### What to avoid:

1. Writing to the same file from multiple threads **without coordination** (e.g., no lock, no queue).
2. Opening the file in **append mode from multiple places** simultaneously.

## Answers

### Answer by ICSM Computer

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:

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

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

### 3. Use `SemaphoreSlim` for async scenarios

```cs
private static readonly SemaphoreSlim fileSemaphore = new SemaphoreSlim(1, 1);

public static async Task WriteToFileAsync(string path, string text)
{
    await fileSemaphore.WaitAsync();
    try
    {
        await File.AppendAllTextAsync(path, text + Environment.NewLine);
    }
    finally
    {
        fileSemaphore.Release();
    }
}
```

### What to avoid:

1. Writing to the same file from multiple threads **without coordination** (e.g., no lock, no queue).
2. Opening the file in **append mode from multiple places** simultaneously.


---

Original Source: https://www.mindstick.com/interview/34102/how-do-you-ensure-thread-safe-access-when-multiple-threads-are-writing-to-the-same-file

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
