我们如何在WinRT应用程序中设置计时器?

我想在我的Windowsapp store应用中设置Timer。

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 } 

在按钮上单击我调用上面的方法来设置此计时器。 但是当设置了Tickhand的Eventhandler时,我收到错误“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”

我们是否需要在Windowsapp store应用中以不同方式处理定时器?

解决方案是将Timer移出方法,例如

 private DispatcherTimer timer = new DispatcherTimer(); 

并在ctor中设置它

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

很难说没有完整代码的原因是什么,但它可能是timer_Tick的行为。