在 c# 中写入控制台:您可以使用多种颜色的单个 writeline,还是锁定控制台以进行多次写入? [英] Writing to console in c#: can you single writeline with multiple colors, or lock the console to do multiple writes?

查看:50
本文介绍了在 c# 中写入控制台:您可以使用多种颜色的单个 writeline,还是锁定控制台以进行多次写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个具有不止一种颜色的字符串放到控制台上,并让它像单个 WriteLine 一样执行,而不是多次写入可能会被其他线程同时写入中断或损坏.

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.

所以下面的帖子看起来朝着正确的方向发展,但我无法控制写入控制台的所有代码.我的代码仅限于我正在创作的 dll,所以我不能在可能干扰的任何地方加锁.如果是关于锁和对线程理解的问题,那就没有问题了.这甚至可能在我的代码中没有锁定吗?

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?

如何锁定控制台C#.NET 中的线程?

推荐答案

使用 Console.SetOut 用您自己的 TextWriter 替换现有的输出流.在您的自定义文本编写器中,让它同步对某个对象的控制台的访问,然后写回真实 标准输出,并为您还必须能够执行的辅助方法提供一些方法在同一个对象上同步,这样每当该辅助方法运行时,它就可以锁定应用程序其余部分对控制台的访问.

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.

这篇关于在 c# 中写入控制台:您可以使用多种颜色的单个 writeline,还是锁定控制台以进行多次写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆