2012-02-01 60 views
1

我正在寻找一种简单的方法,在延迟n秒后执行动作/方法。事情我找到了几个例子,但他们似乎对过于复杂时,我上次平台,iOS设备,这只是延迟n秒后执行动作一次,WP7 C#

[self performSelector:@selector(methodname) withDelay:3]; 

任何提示或代码段将不胜感激。

回答

5

您还可以使用Scheduler.DispatcherMicrosoft.Phone.Reactive

Scheduler.Dispatcher.Schedule(MethodName, TimeSpan.FromSeconds(5)); 

private void MethodName() 
{ 
    // This happens 5 seconds later (on the UI thread) 
} 
4
DispatcherTimer DelayedTimer = new DispatcherTimer() 
{ 
    Interval = TimeSpan.FromSeconds(5) 
}; 
DelayedTimer.Tick += (s, e) => 
{ 
    //perform action 
    DelayedTimer.Stop(); 
} 
DelayedTimer.Start(); 
0
DispatcherTimer timer = new DispatcherTimer(); 

    timer.Tick += (s, e) => 
     { 
      // do some very quick work here 

      // update the UI 
      StatusText.Text = DateTime.Now.Second.ToString(); 
     }; 

    timer.Interval = TimeSpan.FromSeconds(1); 
    timer.Start(); 

注意,你在这里做遮住UI线程,没有真正运行在一个单独的线程东西。它不适合长时间运行和CPU密集型的任何事情,而是适用于需要定期执行的事情。时钟UI更新就是一个很好的例子。

此外,定时器不保证在发生时间间隔时精确执行,但它们保证在时间间隔发生之前不会执行。这是因为DispatcherTimer操作与其他操作一样放在Dispatcher队列中。执行DispatcherTimer操作时,依赖于队列中的其他作业及其优先级。

For more information use this link

如果你想使用定时器后台任务然后使用 System.Threading.Timer代替DispatcherTimer

For more information use this link

1

对于Windows Phone 8你可以使用

await Task.Delay(milliseconds);