我做了一个迷宫游戏。我需要一个滴答作响的计时器。我试图创建一个这样的类:
using System;
using System.Threading;
namespace Maze
{
class Countdown
{
public void Start()
{
Thread.Sleep(3000);
Environment.Exit(1);
}
}
}
并在代码的开头调用 Start() 方法。运行它后,我试图通过失败的迷宫移动化身。如果我没记错的话,Thread.Sleep 会使我的其余代码不再工作。如果我有办法做其他事情,请告诉我。
最佳答案
您当前的代码不工作的原因是调用 Thread.Sleep()
会停止当前线程上的任何执行,直到给定的时间过去。因此,如果您在主游戏线程上调用 Countdown.Start()
(我猜您正在这样做),您的游戏将卡住,直到 Sleep()
调用结束。
相反,您需要使用 System.Timers.Timer
看看 MSDN documentation .
更新:现在希望能匹配更多您的场景
public class Timer1
{
private int timeRemaining;
public static void Main()
{
timeRemaining = 120; // Give the player 120 seconds
System.Timers.Timer aTimer = new System.Timers.Timer();
// Method which will be called once the timer has elapsed
aTimer.Elapsed + =new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 3 seconds.
aTimer.Interval = 3000;
// Tell the timer to auto-repeat each 3 seconds
aTimer.AutoReset = true;
// Start the timer counting down
aTimer.Enabled = true;
// This will get called immediately (before the timer has counted down)
Game.StartPlaying();
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Timer has finished!
timeRemaining -= 3; // Take 3 seconds off the time remaining
// Tell the player how much time they've got left
UpdateGameWithTimeLeft(timeRemaining);
}
}
关于c# - 如何使用 System.Threading.Timer 和 Thread.Sleep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6708857/