2010-08-15 31 views

回答

14

您可以在循環中添加此調用:

System.Threading.Thread.Sleep(5000); // 5,000 ms 

或最好爲更好的可讀性:

System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5)); 

但是,如果你的應用程序的用戶界面,你永遠不應該在前臺線程上睡覺(處理應用程序消息循環的線程)。

+0

工作過的感謝! – Chin 2010-08-15 08:26:57

+3

此代碼將在每次迭代之間等待5秒,而不是每5秒鐘觸發一次。如果您在循環中執行的代碼需要很長時間,例如網絡請求,那麼總數將超過5秒。採用pilot的Timer解決方案對您的問題更爲準確,但任何解決方案都可能適合您的需求。 – 2010-08-15 09:41:09

+1

爲了便於閱讀,Sleep函數還可以將TimeSpan作爲參數。 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5)); – 2010-08-15 09:42:26

10

您可以嘗試使用定時器,

using System; 

public class PortChat 
{ 
    public static System.Timers.Timer _timer; 
    public static void Main() 
    { 

     _timer = new System.Timers.Timer(); 
     _timer.Interval = 5000; 
     _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); 
     _timer.Enabled = true; 
     Console.ReadKey(); 
    } 

    static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     //Do Your loop 
    } 
} 

此外,如果在循環的操作可以持續多則5秒,你可以設置

_timer.AutoReset = false; 

禁用一個時鐘嘀噠,直到循環運行完成
但隨後結束循環的結束,您需要再次啓用定時器像

_timer.Enabled = true; 
4

根本不要使用循環。設置一個Timer對象並對其觸發的事件做出反應。注意,因爲這些事件將在另一個線程(線程池中的定時器線程)上觸發。

1

假設你有一個for環回,你想用於每秒寫入數據庫。然後,我會創建一個定時器,設置爲1000   ms間隔,然後使用定時器的方式與使用while -loop的方式相同,如果要使其像for -loop一樣工作。通過在循環之前創建整數並將其添加到循環中。

public patial class Form1 : From 
{ 
    timer1.Start(); 
    int i = 0; 
    int howeverLongYouWantTheLoopToLast = 10; 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (i < howeverLongYouWantTheLoopToLast) 
     { 
      writeQueryMethodThatIAssumeYouHave(APathMaybe, i); // <-- Just an example, write whatever you want to loop to do here. 
      i++; 
     } 
     else 
     { 
      timer1.Stop(); 
      //Maybe add a little message here telling the user the write is done. 
     } 
    } 
}