2012-02-01 62 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);