Writing to console in c#: can you single writeline with multiple colors, or lock the console to do multiple writes?

那年仲夏 提交于 2019-12-24 15:42:20

问题


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:


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.



来源:https://stackoverflow.com/questions/18896404/writing-to-console-in-c-can-you-single-writeline-with-multiple-colors-or-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!