2012-04-06 64 views
0

我想在预定义的时间过去后重复执行代码,并且我不想通过使用线程搞乱事情。下面的代码是一个好习惯吗?重复执行代码

Stopwatch sw = new Stopwatch(); // sw constructor 
EXIT: 
    // Here I have my code 
    sw.Start(); 
    while (sw.ElapsedMilliseconds < 100000) 
    { 
     // do nothing, just wait 
    } 

    System.Media.SystemSounds.Beep.Play(); // for test 
    sw.Stop(); 
    goto EXIT; 
+2

的坏很好的例子做法;) – sll 2012-04-06 08:54:58

回答

2

你可以使用一个计时器什么俄德建议:

public partial class TestTimerClass : Form 
{ 
    Timer timer1 = new Timer(); // Make the timer available for this class. 
    public TestTimerClass() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     timer1.Tick += timer1_Tick; // Assign the tick event 
     timer1.Interval = 1000; // Set the interval of the timer in ms (1000 ms = 1 sec) 
     timer1.Start(); // Start the timer 
    } 

    void timer1_Tick(object sender, EventArgs e) 
    { 
     System.Media.SystemSounds.Beep.Play(); 
     timer1.Stop(); // Stop the timer (remove this if you want to loop the timer) 
    } 
} 

编辑:只是想向您展示如何使一个简单的计时器,如果你不知道如何:)

4

使用计时器代替标签和StopWatch的。你正在忙着等待,在紧密的循环中捆绑CPU。

你启动一个定时器,给它一个间隔来触发(100000毫秒),然后在Tick事件的事件处理程序中运行你的代码。

请参阅MSDN杂志中的Comparing the Timer Classes in the .NET Framework Class Library