gpt4 book ai didi

c# - 即使在 C# 中繁忙时也强制控制台应用程序进行打印

转载 作者:行者123 更新时间:2023-12-03 12:49:15 24 4
gpt4 key购买 nike

我有一个简单的控制台应用程序,如下所示:

private static void Main (string [] args)
{
System.Console.WriteLine("Initializing context...");
Database.Context.Initialize();

System.Console.WriteLine("Creating server...");
var server = new Server();
server.OnStarting += Server_OnStarting;
server.OnStarted += Server_OnStarted;

System.Console.WriteLine("Starting server...");
server.Start();
}

private static void Server_OnStarting (object sender, EventArgs e)
{
System.Console.WriteLine("Server_OnStarting.");
}

private static void Server_OnStarted (object sender, EventArgs e)
{
System.Console.WriteLine("Server_OnStarted.");
}

服务器启动方法:

public bool Start ()
{
bool result = false;

lock (this._SyncRoot)
{
if (!this.Running)
{
this.Stopwatch.Reset();

this.RaiseOnStarting();

this.Running = true;
this.Terminate = false;
this.ThreadObject = new System.Threading.Thread(new System.Threading.ThreadStart(this.ProcessInternal));

this.Stopwatch.Restart();
this.ThreadObject.Start();

this.RaiseOnStarted();

result = true;
}
}

return (result);
}

输出:

Console Output

三者之中Console.WriteLine来电Main ,只有第一个会立即打印。这是可以理解的,因为 Database.Context.Initialize 中的所有内容发生在同一个线程上。然而,打印Creating server...Starting server...被延迟并与 Server_OnStarting 聚集在一起和Server_OnStarted消息。对构造函数的调用不是线程化的,而是对 server.Start 的调用在内部启动一个线程,初始化一些套接字等。但是,事件 OnStartingOnStarted相同线程上触发,因此它的线程方面应该不重要。

看来,Initializing context...之后打印出来,无论我在哪里调用 Console.WriteLine ,它不会更新控制台窗口,直到 server.Start 在触发这两个事件后返回。

有没有办法在等待服务器启动时强制控制台更新?

最佳答案

Is there a way to force the console to update while waiting for the server to start?

默认情况下,控制台的行为方式如下;事实上,没有(受支持的)机制来强制它以不同的方式表现。当 Console.Out 属性启动时,AutoFlush底层 TextWriter 的属性设置为 true。 AutoFlush 的文档明确指出了这一点(添加了强调):

For example, set AutoFlush to true when you are writing to a device where the user expects immediate feedback. Console.Out is one of these cases: The StreamWriter used internally for writing to Console flushes all its internal state except the encoder state after every call to StreamWriter.Write.

(请注意,无法直接查询 AutoFlush,因为实际实现使用线程安全包装器;但是,您可以使用调试器或反射来检查 ((Console .Out 作为 TextWriter.SyncTextWriter)._out 作为 StreamWriter).AutoFlush 为 true。)


回到原来的问题:

It seems, that after Initializing context... is printed, no matter where I put the call to Console.WriteLine, it does not update the console window until server.Start returns after firing both events.

让我们看看 Server.Start 实际做了什么:

  1. 输入锁定(由于服务器未启动,因此可能是非阻塞的)
  2. ** 引发 OnStarting 事件**
  3. 启动一个线程
  4. 重新启动秒表
  5. ** 引发 OnStarted 事件**
  6. 返回

这些任务都不是特别密集。 OnStarting 和 OnStarted 调用之间的延迟可能在微秒范围内。

这三个状态消息看起来会同时打印,因为在服务器实例化、进入 Server.Start 方法和从 Server.Start 返回之间没有明显的时间流逝 方法。

关于c# - 即使在 C# 中繁忙时也强制控制台应用程序进行打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com