Middle
How to write text to a file simultaneously from two different tasks? How to synchronize access?
sobes.tech AI
Answer from AI
To write text to a file from two different tasks (threads) in C#, it is necessary to synchronize access to the file to avoid conflicts and data corruption.
The simplest way is to use a lock object for sequential access:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static readonly object fileLock = new object();
private const string filePath = "output.txt";
static void WriteToFile(string text)
{
lock (fileLock)
{
File.AppendAllText(filePath, text + Environment.NewLine);
}
}
static void Main()
{
Task t1 = Task.Run(() => {
for (int i = 0; i < 10; i++)
{
WriteToFile($"Task 1 - Line {i}");
Thread.Sleep(50);
}
});
Task t2 = Task.Run(() => {
for (int i = 0; i < 10; i++)
{
WriteToFile($"Task 2 - Line {i}");
Thread.Sleep(50);
}
});
Task.WaitAll(t1, t2);
}
}
In this example, lock ensures that only one task writes to the file at a time, preventing simultaneous access.
Alternatively, you can use SemaphoreSlim or other synchronization mechanisms, but lock is the simplest and most effective for such cases.