2015-02-10 59 views
0

在我的控制檯應用程序下方的while循環中,調用GenerateRandomBooking()方法5次然後延遲GenerateRandomBids() 2-3秒的最佳方式是什麼?運行方法幾次,並延遲幾秒

private static void Main() 
    { 
     SettingsComponent.LoadSettings(); 

     while (true) 
     { 
      try 
      { 
        GenerateRandomBooking(); 
        GenerateRandomBids(); 
        AllocateBids(); 
        Thread.Sleep(TimeSpan.FromSeconds(5)); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.ToString()); 
      } 
     } 
    } 
+1

你試過'Thread.Sleep(毫秒)'?一旦你問(*最好的方法*),你至少應該提供一種方法。 +它幾乎每次都是基於意見的 – chouaib 2015-02-10 08:48:03

回答

4

大約是這樣的

private static void Main() 
{ 
    SettingsComponent.LoadSettings(); 

    while (true) 
    { 
     try 
     { 
      for(int x=0; x<4 ; x++){ 
       GenerateRandomBooking(); // Will call 5 times 
      } 

      Thread.Sleep(2000) // 2 seconds sleep 

      GenerateRandomBids(); 

      AllocateBids();   
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 

    } 
} 
+0

在繼續之前它如何調用GenerateRandomBooking();五次? – methuselah 2015-02-10 09:17:24

+0

檢查更新後的答案。我以不同的方式閱讀/理解你的問題。希望這會有所幫助 – 2015-02-10 09:24:17

2
使用 Thread.Sleep()

是什麼幾乎總是一個壞主意。我相信這是更好的使用計時器:

System.Timers.Timer timer = new System.Timers.Timer(); 

timer.Interval = 2000; 
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); 
timer.Enabled=false; 
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)  
{ 
    timer.Enabled=false; 
} 

private static void Main() 
{ 
    SettingsComponent.LoadSettings(); 

    int counter =0; 

    while (true) 
    { 
     try 
     { 
      GenerateRandomBooking(); 
      GenerateRandomBids(); 
      AllocateBids(); 
      counter ++;    

      if(counter > 4){ 
       timer.Enabled=true; 
       while (timer.Enabled) 
       { 
        ///wait time equal to timer interval... 
       } 
       counter=0; 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 

    } 
} 
+0

爲什麼總是一個壞主意?會發生什麼? – methuselah 2015-02-10 09:17:43

+1

檢查此:http://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful – apomene 2015-02-10 09:23:28

+0

感謝您的答覆 – methuselah 2015-02-10 09:59:32

相關問題