Reputation: 5468
I am building a C#
console application and want to customize the prelude symbol to something else such as "> ". I checked the properties of class Console
and could not find any one doing this job. As a workaround, in the code I write a "> " symbol before writing any new line. But this is not a perfect solution, especially when there is a background worker thread printing messages, sometimes the prelude symbol will be lost because the work thread may write message earlier before the main thread writing a prelude.
I searched web but did not find any hint, is there a standard solution for this?
Upvotes: 2
Views: 1902
Reputation: 5851
If this is not possible out of the box, I would suggest to provide an custom class that encapsulates the Console
class that you will use from within the background threads to write messages to the console. This will also make unit testing easier.
public class ClassInOtherThread
{
private readonly IConsoleWriter _consoleWriter;
public ClassInOtherThread(IConsoleWriter consoleWriter)
{
this._consoleWriter = consoleWriter;
}
public void DoSomething()
{
_consoleWriter.Write("something");
}
}
public interface IConsoleWriter
{
void Write(string value);
}
public class ConsoleWriter : IConsoleWriter
{
public void Write(string value)
{
// Fix your > problems in this class
Console.Write(value);
}
}
Upvotes: 2
Reputation: 6984
is there a standard solution for this?
No.
Aphelion hits the nail on the head when he says to create a custom class to handle this.
public static class I
{
public string preclude = ">";
public static void WriteLine(string message)
{
Console.WriteLine(preclude+message);
}
public static void ReadLine()
{
Console.Write(preclude);Console.ReadLine();
}
}
Because you have a background thread writing to the console you should also have a check to make sure you don't have conflicting write lines such as when you ask for user input. You will have to implement Console.MoveBufferArea
in your thread which writes while the user is asked for input otherwise you will have an issue if the user is in the middle of typing.
It will be easy to update in your code too just replace Console.WriteLine with I.Console.WriteLine.
Upvotes: 1