开发者

What happens if I call Start() two times on class System.Windows.Forms.Timer?

Imagine that I have a System.Windows.Forms.Timer with 1000 ms interval.

If I call Timer.Start() met开发者_如何学Gohod and after 500 ms I call again Timer.Start() what happens? The second Start call will reset the interval or not? Are there any side effects?


The timer is already started, so a second call will not affect it.

Regardless, this is easy to test.


Start() just sets the Enabled property to true. If the Enabled property is already set to true it just sets Enabled to true again and keeps going.

Likewise, Stop() sets Enabled to false.


It won't affected anything...

See this code

  class TimerTest
{
   static int i = 0;
    static void Tick(object sender, EventArgs e)
    {

        Console.WriteLine(i);
        i++;
    }
    static void Main()
    {
        // interval = 500ms
        Timer tmr = new Timer();
        tmr.Interval = 500;
        tmr.Elapsed += Tick;
        tmr.Start();
        Console.ReadLine();
        tmr.Start();
        Console.ReadLine();
        tmr.Stop();
        Console.ReadLine();
        tmr.Start();
        Console.ReadLine();
        tmr.Dispose(); // This both stops the timer and cleans up.
    }
}

once u started, if Enter return the second start won't affect anything.


Those answering that Start() "just sets the Enabled property to true" are overlooking that Enabled is a property and that all of the start logic is in the set accessor. So, there is no "just" about it. Looking at the reference source makes it clear that if you set Enabled to the same value that it already has then nothing happens, it's a nop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜