Console.WriteLine是否阻塞? [英] Does Console.WriteLine block?

查看:1143
本文介绍了Console.WriteLine是否阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




解决方案


是否有一个方法将异步输出写入控制台?Console.WriteLine直到
输出已经写入或者
立即返回?





如果它阻塞了有一个
的方法写异步输出到
控制台?


如果使用.NET 4.0,写入控制台而不阻塞的解决方案是非常简单的。想法是排队文本值,让一个专用线程做 Console.WriteLine 调用。生产者 - 消费者模式在这里是理想的,因为它保留了当使用本地 Console 类时隐含的时序。 .NET 4.0让这个很容易的原因是它有 BlockingCollection 促进生产者 - 消费者模式的生产的类。如果您不使用.NET 4.0,那么您可以通过下载 Reactive扩展框架。

  public static class NonBlockingConsole 
{
private static BlockingCollection< string& m_Queue = new BlockingCollection< string>();

static NonBlockingConsole()
{
var thread = new Thread(
()=>
{
while .WriteLine(m_Queue.Take());
});
thread.IsBackground = true;
thread.Start();
}

public static void WriteLine(string value)
{
m_Queue.Add(value);
}
}


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?

解决方案

Does Console.WriteLine block until the output has been written or does it return immediately?

Yes.

If it does block is there a method of writing asynchronous output to the Console?

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是否阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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