如何使用线程同时在控制台上读/写
本文关键字:控制台 何使用 线程 | 更新日期: 2023-09-27 18:09:01
我想实现一个运行模拟的c#控制台应用程序。另外,我想让用户有机会在控制台上按"+"或"-"来加速/减速模拟的速度。
是否有一种方法来读取控制台,而写在它上?我相信我可以使用多线程,但我不知道如何做到这一点(我仍然是c#的新手)。
非常感谢!
您可以查看控制台。在呼叫Console.ReadKey()
之前可用。这将让您检查控制台,看看是否有输入等待(即:用户按下+或-)而不阻塞。如果你在没有可用输入的情况下不尝试读取,你的主线程将永远不会阻塞等待用户。
是的,有一种方法可以在"同时"读/写。有几种方法可以做到这一点:
使用另一个线程:
首先,启动一个负责向控制台写入的线程。
Thread t = new Thread(()=>{RunSimulation();});
t.IsBackground = true;
t.Start();
模拟方法看起来像这样:
public void RunSimulation()
{
while(running)
{
// Puts the thread to sleep depending on the run speed
Thread.Sleep(delayTime);
Console.WriteLine("Write your output to console!");
}
}
第二,你可以不断地让主线程轮询用户输入,以便做出调整。
string input = string.Empty;
while(input.Equals("x", StringComparison.CurrentCultureIgnoreCase)
{
input = Console.ReadKey();
switch(input)
{
case "+":
// speeds up the simulation by decreasing the delayTime
IncreaseSpeed();
break;
case "-":
// slows down the simulation by decreasing the delayTime
DecreaseSpeed();
break;
default:
break;
}
}
使用定时器:
另一种方法是使用[Timer][1]并调整计时器上回调的频率,而不是调整线程上的睡眠时间:
// Create the timer
System.Timers.Timer aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnPrintSimulationResult);
// Change the Interval to change the speed of the simulation
aTimer.Interval = 2000; // <-- Allows you to control the speed of the simulation
aTimer.Enabled = true;
当然,您必须处理线程安全问题,但这应该为您提供了一个体面的起点。一旦你尝试了其中一种方法,并且遇到了具体的问题,你可以回来,我相信人们会很乐意解决你遇到的任何特殊问题。请注意,在控制台中执行此操作并不是一个非常美观的解决方案,但它可以工作。如果您想要更优雅的东西,那么只需创建一个具有文本区域的GUI应用程序,将控制台输出重定向到文本区域,并添加2个按钮(+/-)来调整速度。[1]: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx