Search code examples
.netwpf

Timer tick event continue or exit


I wonder the problem, is when I call the Timer event:

DispatcherTimer Timer = new DispatcherTimer();
                Timer.Tick += (s, e) =>
              {
               
                  MyCode();
                  Timer.Stop();
              };

Timer.Start();
Timer.Interval = TimeSpan.FromSeconds(10);

private static void MyCode() { /* EXAMPLE MY CODE RUN */ }

So will my MyCode run out of thread before Timer.Stop() or not?


Solution

  • There are a few problems with your code:

    • You start the timer before you set the interval, so the Tick event will be triggered immediately rather than after 10 sec.
    • The DispatcherTimer does not have a Close method. You probably mean Stop?
    • In the Tick event, you call MyCode before you stop the Timer. It is probably better to first stop the Timer, before you call MyCode.

    So a suggestion for your code:

    DispatcherTimer Timer = new { Interval = TimeSpan.FromSeconds(10) };
    Timer.Tick += (s, e) =>
              {               
                  Timer.Stop();
                  MyCode();
              };
    Timer.Start();
    ...
    
    private static void MyCode() { /* EXAMPLE MY CODE RUN */ }