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

12

我正在尝试在我的Windows Store应用程序中设置计时器。

    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      
      }
当我点击按钮时,我调用上述方法来设置计时器。但是当为Tick事件处理程序设置EventHandler时,出现错误 "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
我们在Windows Store应用程序中需要以不同的方式处理计时器吗?

如果将计时器(timer)设置为字段(field),并将timer.Tick += timer_Tick; timer.Interval = new TimeSpan(00, 1, 1);移动到构造函数中,会发生什么?同时,bool enabled = timer.IsEnabled;没有效果,对吗? - Lukasz Madon
1
@lukas 抱歉,我没有理解你的第一点。能否请您详细说明一下? - Sap
2
私有的 DispatcherTimer 计时器 = new DispatcherTimer(); public YourClass() { 计时器.Tick += timer_Tick; 计时器.Interval = new TimeSpan(00, 1, 1); } - Lukasz Madon
它修复了问题或帮助找到了原因? - Lukasz Madon
要运行DisptcherTimer Async,您可以参考此链接[这里] 1 - Rahul Saksule
显示剩余2条评论
1个回答

11
解决方案是将计时器移出该方法,例如:
private DispatcherTimer timer = new DispatcherTimer();

并在构造函数中设置它

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

没有完整的代码很难确定原因,但可能是timer_Tick的行为导致的。


它的缺点是它在UI线程上运行。因此,如果计时器事件执行时间/ CPU消耗任务,则UI会稍微停顿。 - Tilak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接