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

问题描述 投票:0回答:5

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

using System;
using System.Threading;

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

并在代码开始处调用 Start() 方法。运行后,我尝试移动头像穿过迷宫,但失败了。如果我没记错的话,Thread.Sleep 会使我的其余代码不再工作。如果我可以做其他事情,请告诉我。

c# timer
5个回答
4
投票

当前代码不起作用的原因是调用

Thread.Sleep()
会停止当前线程上的任何执行,直到给定的时间过去。因此,如果您在主游戏线程上调用
Countdown.Start()
(我猜您正在这样做),您的 game 将冻结,直到
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);
     }
 }

1
投票

您正在寻找

Timer
课程。


1
投票

为什么不使用 BCL 中已包含的 Timer 类之一?

这里是不同类型的比较(MSDN 杂志 - 比较 .NET Framework 类库中的计时器类)。阅读它,看看哪一个最适合您的具体情况。


0
投票

除了@Slaks resposnse 可以说你可以使用:

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

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

问候。


0
投票

请检查下面的链接并了解如何使用主线程中的多个计时器或使用多线程来实现它。希望这足够清楚..

https://stackoverflow.com/a/27356365/2282974

https://stackoverflow.com/a/67364695/2282974

© www.soinside.com 2019 - 2024. All rights reserved.