【发布时间】:2012-01-22 18:09:35
【问题描述】:
这是我想出的在控制台中暂停/恢复活动线程的解决方案......
它需要第二个线程用于输入,主循环也会做出反应。但是我对 C# 的无知让我想知道是否有更简单的解决方案?也许可以单独使用主线程来完成?
基本上,我正在测试几件将以定义的 FPS 进行迭代的东西,并且我希望能够通过键盘输入暂停和恢复迭代。任何反馈都表示赞赏。
class TestLoops
{
int targetMainFPS = 5;
int targetInputFPS = 3;
bool CONTINUE = true;
Thread testLoop, testLoop2;
ConsoleKeyInfo cki;
ManualResetEvent resetThread = new ManualResetEvent(true); //How to correctly pause threads in C#.
public void Resume() { resetThread.Set(); }
public void Pause() { resetThread.Reset(); }
public TestLoops()
{
//_start = DateTime.Now.Ticks;
Console.Write("CreatingLoop...");
this.testLoop = new Thread(MainLoop);
this.testLoop.Start();
this.testLoop2 = new Thread(InputLoop);
this.testLoop2.Start();
}
void MainLoop()
{
long _current = 0;
long _last = 0;
Console.Write("MainLoopStarted ");
while(CONTINUE)
{
resetThread.WaitOne();
_current = DateTime.Now.Ticks / 1000;
if(_current > _last + (1000 / targetMainFPS) )
{
_last = _current;
//Do something...
Console.Write(".");
}
else
{
System.Threading.Thread.Sleep(10);
}
}
}
void InputLoop()
{
long _current = 0;
long _last = 0;
Console.Write("InputLoopStarted ");
while(CONTINUE)
{
_current = DateTime.Now.Ticks / 1000;
if(_current > _last + (1000 / targetInputFPS))
{
_last = _current;
//Manage keyboard Input
this.cki = Console.ReadKey(true);
//Console.Write(":");
if(this.cki.Key == ConsoleKey.Q)
{
//MessageBox.Show("'Q' was pressed.");
CONTINUE = false;
}
if(this.cki.Key == ConsoleKey.P)
{
this.Pause();
}
if(this.cki.Key == ConsoleKey.R)
{
this.Resume();
}
}
else
{
System.Threading.Thread.Sleep(10);
}
}
}
public static void Main(string[] args)
{
TestLoops test = new TestLoops();
}
}
【问题讨论】:
-
帧速率通常不会通过暂停任意值(如您选择的 10 毫秒)来维持。无论暂停/恢复功能如何,您实际上想要完成什么?
-
没有什么比重复一些事情直到我对我所看到的感到满意(在这种情况下重复骰子机制的结果)。它主要用于测试。但是,我正在努力学习,如果有更合适的方法,我想学习。
-
好奇...为什么要从我的标题中删除 C#? ://
标签: c# multithreading input console