12

I am trying to set Timer in my Windows Store App.

    public void Start_timer()
    {

        Windows.UI.Xaml.DispatcherTimer timer = new DispatcherTimer();           
        timer.Tick += new Windows.UI.Xaml.EventHandler(timer_Tick);
        timer.Interval = new TimeSpan(00, 1, 1);
        bool enabled = timer.IsEnabled;              // Enable the timer
        timer.Start();                              // Start the timer      
      }

On button click I call above method to set this Timer. But when Eventhandler for Tick is set, I get error "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Do we need to handle Timers differently in Windows Store apps?

Richard Garside
  • 87,839
  • 11
  • 80
  • 93
Sap
  • 179
  • 1
  • 4
  • 10
  • What will happen if you make timer a filed, and timer.Tick += timer_Tick; timer.Interval = new TimeSpan(00, 1, 1); move to contructor. Also bool enabled = timer.IsEnabled; has no effect, does it? – Lukasz Madon Jan 31 '12 at 16:18
  • 1
    @lukas Sorry, didn't get your first point.Could you please elaborate – Sap Feb 01 '12 at 03:42
  • 2
    private DispatcherTimer timer = new DispatcherTimer(); public YourClass() { timer.Tick += timer_Tick; timer.Interval = new TimeSpan(00, 1, 1); } – Lukasz Madon Feb 01 '12 at 12:55
  • it fixed the issue or helped to find the cause? – Lukasz Madon Feb 02 '12 at 10:18
  • fixed it. No above exception anymore. – Sap Feb 03 '12 at 03:40
  • You should mark the correct answer to help other users get the right indications to solve similar problems – Gabber Apr 03 '12 at 12:55
  • For running DisptcherTimer Async you can refer this link [Here][1] [1]: http://stackoverflow.com/questions/12442622/async-friendly-dispatchertimer-wrapper-subclass – Rahul Saksule Jul 10 '13 at 07:22

1 Answers1

11

The solution is to move the Timer out of the method e.g

private DispatcherTimer timer = new DispatcherTimer();

and set it up in the ctor

public TheClass()
{
    timer.Tick += timer_Tick; 
    timer.Interval = new TimeSpan(00, 1, 1);
    timer.Start();
}

Hard to tell what is the reason without the full code, but it could be the behavior of the timer_Tick.

whihathac
  • 1,741
  • 2
  • 22
  • 38
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108
  • its disadvantage is that it runs on UI thread. So if timer event is executing time/cpu consuming task, UI hangs a bit – Tilak May 08 '12 at 05:53