简体   繁体   中英

Stop a looped thread method after x seconds

I'm creating a console game as simple as "I generate a random number, find it", but with many options.

My current code (without what I want here) is availlable on GitHub: https://github.com/crakmaniaque/trouvezmoi

What I want is to create a version of my game which will be timed, so the computer generates numbers, the user finds it, it generates a new one and the player have 90 seconds to find a max lot of random numbers. I can code this easily.

What I will need help is to stop the game (a thread) after 90 seconds and retrieve the number of answers founded from the thread. The Console.Title should also show time remaining. The attempt I've tried works, but the thread is not interrupted if console is asking for number input ( Console.ReadLine() ). But the timer is for the entire process, not only user input.

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.");
            }
        }
    }
}

I don't know much about threading and at that point I'm stuck. Can someone help me with my problem? I'm using .NET 2.0.

Perhaps you are looking for a timer? You could register an event, that would fire after 90 seconds, that would run while the loop is happening. The documentation can be found here: Timer class MSDN documentation .

I believe the usage would be:

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

You'd need to make each console read with a timeout equal to the amount of time left in the game. That solves that issue.

Then, you need a way to signal the timerb thread to shut down when the main game loop has ended. I think the simplest way would be to end the game loop when the remaining time is <= zero. Alternatively, you could make timerb singnal the main thread to shut down when t == 0 . Inter-thread communication is always complicated and error-prone, though.

You can signal the timerb thread to shut down by setting a volatile bool shutdown to true and by making timerb poll that variable and shut itself down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM