Is `Console.Error.WriteLine` thread-safe in C#?

Responsive Ad Header

Question

Grade: Education Subject: Support
Is `Console.Error.WriteLine` thread-safe in C#?
Asked by:
47 Viewed 47 Answers

Answer (47)

Best Answer
(512)
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); } } ```