Question
Is `Console.Error.WriteLine` thread-safe in C#?
Asked by: USER2557
47 Viewed
47 Answers
Answer (47)
No, `Console.Error.WriteLine` is not inherently thread-safe. If multiple threads attempt to write to the console error stream simultaneously, the output may become interleaved or corrupted. To ensure thread safety, you should use a locking mechanism (e.g., `lock` statement) to synchronize access to the console error stream. Example:
```csharp
private static readonly object _lock = new object();
public static void LogError(string message)
{
lock (_lock)
{
Console.Error.WriteLine(message);
}
}
```