How to block console through threads in C # .NET?

I have a logger class that handles a different information display with pretty colors (yay.). However, since it writes to the console in divided steps (i.e., sets the color to red, writes text, sets the color to gray, writes text for something that would display "[Error] Description ... "with an error in red), but I have a multi-threaded application, so the steps can be mixed and print random things in random colors.

I know the lock keyword, however it will not work with a static class such as a console.

Here is a sample code if I do not understand:

 using System; using System.Text; namespace N.Utilities.IO { public static class Logger { private static void WriteColored(string value, ConsoleColor color) { if (Logger.UseColor) { Console.ForegroundColor = color; Console.Write(value); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.Write(value); } } private static void WriteLineColored(string value, ConsoleColor color) { if (Logger.UseColor) { Console.ForegroundColor = color; Console.WriteLine(value); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.Write(value); } } private static bool useColor = true; public static bool UseColor { get { return Logger.useColor; } set { Logger.useColor = value; } } public static void Inform(string value) { Logger.WriteColored(" [Info] ", ConsoleColor.White); Console.WriteLine(value); } public static void Warn(string value) { Logger.WriteColored(" [Warning] ", ConsoleColor.Yellow); Console.WriteLine(value); } public static void Error(string value) { Logger.WriteColored(" [Error] ", ConsoleColor.Red); Console.WriteLine(value); } } 
+9
source share
1 answer

For your class you need:

 private static readonly object ConsoleWriterLock = new object(); 

You can then lock this before recording to the console.

 lock(ConsoleWriterLock) { //Your code here } 

The lock keyword will work with a static class, you just need to provide a static readonly object to lock.

+19
source

Source: https://habr.com/ru/post/1411751/


All Articles