如何使用System.Threading.Timer和Thread.Sleep

本文关键字:Thread Sleep Timer Threading 何使用 System | 更新日期: 2023-09-27 18:02:38

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

using System;
using System.Threading;
namespace Maze
{
    class Countdown
    {
        public void Start()
        {
            Thread.Sleep(3000);              
            Environment.Exit(1);
        }
    }
}

,并在代码开头调用Start()方法。在运行它之后,我尝试着通过迷宫移动角色,但是失败了。如果我没记错的话,丝线。睡眠会使我的其他代码不再工作。如果我能做其他事情,请告诉我

如何使用System.Threading.Timer和Thread.Sleep

当前代码不能工作的原因是调用Thread.Sleep()会停止当前线程上的任何执行,直到给定的时间过去。所以如果你在你的主游戏线程上调用Countdown.Start()(我猜你正在做),你的游戏将冻结,直到Sleep()调用完成。


相反,您需要使用System.Timers.Timer

查看MSDN文档

更新:现在希望更符合您的场景

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

您要找的是Timer

为什么不使用一个已经包含在BCL中的Timer类呢?

下面是不同定时器类的比较(MSDN杂志-比较。net框架类库中的定时器类)。阅读它,看看哪一个最适合你的具体情况。

除了@Slaks回复可以说你可以使用:

  1. System.Windows.Forms.Timer是在UI停留的同一线程上的定时器
  2. System.Timers.Timer这是一个定时器,但在另一个线程上运行。

选择取决于你,取决于你的应用程序架构。

问候。