2011-07-15 48 views
3

我做了一个迷宫游戏。我需要一个滴答定时器。我试图创建一个这样的类:如何使用System.Threading.Timer和Thread.Sleep?

using System; 
using System.Threading; 

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

并在代码开始时调用Start()方法。运行后,我试图将头像移动到失败的迷宫中。如果我没有弄错,Thread.Sleep会让我的其他代码不再工作。如果有办法,我可以做其他事情,请告诉我。

+0

你能告诉我们更多的代码,例如你如何设置更新和绘制循环? – TJHeuvel

+0

是滴答定时器,用于控制玩家通过迷宫玩了多少时间? – nbz

+0

@Reinan - 您所有的代码都会将调用线程(您的应用程序)置于睡眠状态3秒钟。你需要一个独立的线程,让它进入睡眠状态,等待它醒来,然后再做任何事情。只需使用Timer类。 –

回答

1

您正在寻找Timer类。

+0

? Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000); –

1

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

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

+0

我真的不明白如何使用Start()Stop()方法。它是否已经内置?像Read()和Write()?或者我仍然需要创建自己的方法Start()? –

+0

@Reinan Contawi - 你读过链接的文章了吗?它有例子。所有计时器都使用_events_来触发。 – Oded

+0

仅适用于Form Applications?我使用控制台应用程序btw。 –

2

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


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

看一看的MSDN documentation

UPDATE:现在希望更符合您的方案

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

什么是OnTimedEvent?它会在3秒后退出程序吗? –

+0

一旦定时器的时间间隔过去,无论你放在'OnTimedEvent'中什么都会执行。换句话说,你告诉C#'在3000ms之后运行这个代码已经被淘汰了'。 设置'aTimer.Enabled = true'是实际启动定时器倒计时的行。 –

+0

抱歉,您必须有错误的想法,因为我的解释并不那么简洁。我使用的代码只是一个尝试。我知道它会失败,我只是想学习这个概念。我想要发生的事情是我在3秒内做了其他事情。 –

0

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

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

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

问候。

+1

如果您不断与UI进行交互,那么在另一个线程中运行计时器可能更有利。 – nbz

+0

同意@nEM,但最终desicion只有你自己@Reinan。 – Tigran

+0

帮助我从顶部,所以我可以得到的概念。我是一名快速学习者,我只需要从顶端获得它。首先,我的附加头文件是否正确? System.Threading; System.Timers; –