在x秒后停止循环线程方法

时间:2015-08-08 19:53:12

标签: c# multithreading

我创建一个简单的控制台游戏"我生成一个随机数,找到它",但有很多选项。

我目前的代码(没有我想要的)可以在GitHub上使用:https://github.com/crakmaniaque/trouvezmoi

我想要的是创建一个定时的游戏版本,以便计算机生成数字,用户找到它,生成新的数据,玩家有90秒的时间来查找最多的随机数。我可以轻松编写代码。

我需要帮助的是在90秒后停止游戏(一个线程)并检索从该线程建立的答案数量。 Console.Title还应显示剩余时间。我尝试过的尝试有效,但如果控制台要求输入数字(Console.ReadLine()),则线程不会中断。但计时器适用于整个过程,而不仅仅是用户输入。

private static void timerb()
{
     int t = 90;
     for (int i = 0; i < 90; i++)
     {
         Console.Title = t + " seconds remaining";
         Thread.Sleep(1000);
         t--;
     }
}
private static void cGame()
{
    Thread t = new Thread(timerb);
    t.Start();
    while (t.IsAlive)
    {
        bool good = false;
        int rnd = new Random().Next(0,10); // 0 and 10 are sample 
        while (!good)
        {
            try
            {
                Console.Write("Enter a number between x and y >");
                int i = int.Parse(Console.ReadLine());
                if (i == rnd)
                {
                    good = true;
                }
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid answer.");
            }
        }
    }
}

我对线程知之甚少,在那一点上我被卡住了。 有人可以帮我解决我的问题吗?我使用的是.NET 2.0。

2 个答案:

答案 0 :(得分:0)

也许您正在寻找计时器?您可以注册一个事件,该事件将在90秒后触发,该事件将在循环发生时运行。可以在此处找到文档:Timer class MSDN documentation

我相信用法是:

Timer timer = new Timer { Interval = new Timespan (0,1,30);
timer.elapsed += //function to fire to kill the app or the game

答案 1 :(得分:0)

You'd need to make each console read with a timeout equal to the amount of time left in the game.解决了这个问题。

然后,您需要一种方法来通知timerb线程在主游戏循环结束时关闭。我认为最简单的方法是在剩余时间<= 0时结束游戏循环。或者,您可以使timerb singnal成为t == 0时关闭的主线程。但是,线程间通信总是很复杂且容易出错。

您可以通过将volatile bool shutdown设置为true并使timerb轮询该变量并关闭自身来发信号通知timerb线程关闭。

相关问题