c# - 如何使用 System.Threading.Timer 和 Thread.Sleep?

标签 c# timer

我做了一个迷宫游戏。我需要一个滴答作响的计时器。我试图创建一个这样的类:

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/

相关文章:

c - 带有自旋锁的定时器卡住

c# - 如何将端口 IAX2 的 UDP header 转换为可读字符串

.net - 禁用 System.Threading.Timer 的最佳方法

unity-game-engine - 在 Unity 中重复音频剪辑,间隔越来越小

C# csv文件到数组

javascript - ReactJS:单击按钮时调用计时器函数

f# - 仅在 F# Interactive 中声明变量需要 300 毫秒?

c# - 有什么方法可以用 ClrMD 获取局部变量的值(比如 sosex !mdv)?

c# - 非静态方法需要一个目标。找不到似乎有效的答案

c# - 在 C# 中将 ODBC MySQL 字符串替换为 SQL Server 字符串