0

I'm trying to create a timer for my C#/Xaml modern UI app (Windows 8.1).

I already saw this post : How do we set Timers in WinRT app? The solution which is given in this link works for me. The DispatcherTimer works fine.

But my problem isn't there. I don't understand why this solution doesn't works :

My code :

//First Try
        System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false);
        StatusChecker statusChecker = new StatusChecker(MyList);
        System.Threading.TimerCallback tcb = statusChecker.CheckStatus;
        //System.Threading.Timer myTimer = new System.Threading.Timer(tcb, autoEvent, 0, 5000);
        System.Threading.Timer theTimer = new System.Threading.Timer(CheckStatus, autoEvent, 0, 5000);    

I put it in the MainPage constructor. TimerTick launchs CheckStatus which launchs a Debug.WriteLine().

I beleived the Threading.Timer will be set in a different thread than the UI thread but, when I push a button, the timer stops to work.

Somebody knows why ?

Community
  • 1
  • 1
Vilo
  • 29
  • 7
  • 1
    It is never correct to store a System.Threading.Timer object in a local variable. That cannot keep the timer alive, that reference is gone when your method returns. Sooner, actually. With no reference left, the garbage collector collects the Timer object and your callback stops being called. You have to store it in a field of a class whose object is alive long enough. A static variable, if you have to. Now where's that duplicate... Later. – Hans Passant Sep 17 '14 at 15:59
  • Indeed, if I store it in a class's field the problem is solves. Thank you for your help. I will see more explanation about the System.Threading, it's not very clear for me maybe :) – Vilo Sep 18 '14 at 17:32

0 Answers0