我正在尝试在我的Windows应用商店应用中设置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时,我会收到错误 “试图读取或写入受保护的内存。这通常表明其他内存已损坏。”
我们是否需要在Windows应用商店应用中以不同方式处理定时器?
答案 0 :(得分:10)
解决方案是将Timer移出方法,例如
private DispatcherTimer timer = new DispatcherTimer();
并将其设置在ctor
中public TheClass()
{
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(00, 1, 1);
timer.Start();
}
很难说没有完整代码的原因是什么,但它可能是timer_Tick的行为。