Writing to console in c#: can you single writeline

2019-07-24 15:35发布

I want to put a string with more than one color onto the console and have it perform as if it were a single WriteLine, as opposed to multiple writes which could get interrupted, or corrupted by other threads writing at the same time.

So the post below looked like it was going in the right direction, but I do not control all the code that is writing to the console. My code is restricted to the dll that I am authoring, so I can't just go putting locks everywhere that could interfere. If it were a question of locks and understanding of threading there would be no question. Is this even possible without locks in my code?

How do I lock the console across threads in C#.NET?

1条回答
Lonely孤独者°
2楼-- · 2019-07-24 15:54

Replacing the existing output stream with a TextWriter of your own using Console.SetOut. In your custom text writer have it synchronize access to the console on some object and then write back to the real standard output, as well as providing some means for the helper method that you have to also be able to synchronize on that same object, that way whenever that helper method is running it can lock access to the console for the rest of the application.

查看更多
登录 后发表回答