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

Sap*_*Sap 11 c# windows-8 windows-runtime

我正在尝试在我的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      
      }
Run Code Online (Sandbox Code Playgroud)

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

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

Luk*_*don 10

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

private DispatcherTimer timer = new DispatcherTimer();
Run Code Online (Sandbox Code Playgroud)

并在ctor中设置它

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

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