问题描述
确实 Console.WriteLine
块,直到输出已被写入或不会立即返回?
如果它确实是块写有异步输出到控制台的方法?
是的。
要解决写到控制台没有阻塞是出奇的平凡的,如果您使用的是.NET 4.0。我们的想法是要排队文本值,让一个专门的线程执行 Console.WriteLine
通话。生产者 - 消费者模式是理想的位置,因为它preserves时间顺序使用本机控制台
上课的时候是隐含的。之所以.NET 4.0,使这个简单是因为它具有 BlockingCollection 类,它有利于生产生产者 - 消费者模式。如果您不使用.NET 4.0,那么你可以通过下载href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx" rel="nofollow">无扩展的框架。
公共静态类NonBlockingConsole
{
私有静态BlockingCollection<字符串> m_Queue =新BlockingCollection<字符串>();
静态NonBlockingConsole()
{
VAR线程=新主题(
()=>
{
而(真)Console.WriteLine(m_Queue.Take());
});
thread.IsBackground = TRUE;
thread.Start();
}
公共静态无效的WriteLine(字符串值)
{
m_Queue.Add(值);
}
}
Does Console.WriteLine
block until the output has been written or does it return immediately?
If it does block is there a method of writing asynchronous output to the Console?
Yes.
The solution to writing to the console without blocking is surprisingly trivial if you are using .NET 4.0. The idea is to queue up the text values and let a single dedicated thread do the Console.WriteLine
calls. The producer-consumer pattern is ideal here because it preserves the temporal ordering that is implicit when using the native Console
class. The reason why .NET 4.0 makes this easy is because it has the BlockingCollection class which facilitates the production of a producer-consumer pattern. If you are not using .NET 4.0 then you can get a backport by downloading the Reactive Extensions framework.
public static class NonBlockingConsole
{
private static BlockingCollection<string> m_Queue = new BlockingCollection<string>();
static NonBlockingConsole()
{
var thread = new Thread(
() =>
{
while (true) Console.WriteLine(m_Queue.Take());
});
thread.IsBackground = true;
thread.Start();
}
public static void WriteLine(string value)
{
m_Queue.Add(value);
}
}
这篇关于是否Console.WriteLine块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!