2012-07-24 67 views
5
string connectionstring = "server =SQLVS2\\SQLVS2;database=DDM;Persist Security Info=True;uid=ddmuser;password=User02+Ddm;"; 
    SqlConnection myConnection = new SqlConnection(connectionstring); 
    SqlCommand myCommand = new SqlCommand("GetNullHash", myConnection); 
    myCommand.CommandType = CommandType.StoredProcedure; 
    myConnection.Open(); 
    SqlDataReader rdr = myCommand.ExecuteReader(); 

    while (rdr.Read()) 
    { 
     string filename = @"\\" + rdr.GetString(3); 
     filename = System.IO.Path.Combine(filename, rdr.GetString(2)); 
     filename = System.IO.Path.Combine(filename, rdr.GetString(1)); 
     computeHashh1 abc = new computeHashh1(); 
     Console.WriteLine(abc.computeHash(filename));   
     inserthash insert = new inserthash(); 
     insert.InsertHash(rdr.GetString(1), abc.computeHash(filename), rdr.GetStr(2),rdr.GetString(3)); 

    } 

我怎樣才能使這個循環運行一次在5秒內永遠或直到停止。我如何使5秒暫停的無限循環

回答

12

最簡單的方法是:

while (true) { 
    // code here 
    Thread.Sleep(5000); 
} 

然而,對於更穩健性,我會建議windows serviceproper timer

+0

如何在windows服務中編寫適當的定時器?即時通訊實際上使用Windows服務,但沒有計時器 – tipi 2012-07-24 14:01:13

+0

看看我有'適當的計時器'的鏈接。 – mellamokb 2012-07-24 14:01:47

+0

你怎麼能阻止它? – 2012-07-24 14:06:47

4

嘗試:

while(true) 
{ 
    try 
    { 
     thread.sleep(5000) 
    } 
    catch(Exception e) 
    { 
     //handle the exception 
    } 
} 

其最簡單的。

+0

呃打到它 – Nathaniel 2012-07-24 13:58:10

+0

爲什麼計時器是一個更好的方法? – 2012-07-24 14:44:13

+0

看到這個 - 有一個很好的解釋http://stackoverflow.com/questions/391621/compare-using-thread-sleep-and-timer-for-delayed-execution – Nathaniel 2012-07-24 17:10:39

5

我想包你的代碼,並使用一個Timer對象,這將讓你對定時器本身控制(停止,啓動等)

System.Timers.Timer aTimer; 
aTimer = new System.Timers.Timer(); 
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
aTimer.Interval = 2000; 
aTimer.Enabled = true; 

private void OnTimedEvent(object source, ElapsedEventArgs e) 
{ 
    //your code 
} 

更多信息以

http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.100%29.aspx

+0

爲什麼有人需要停止/啓動無限循環的計時器? – 2012-07-24 14:45:36

+0

OP:我怎樣才能讓這個循環在5秒內運行一次,或者直到停止。 – 2012-07-24 15:04:17

+0

'5秒永遠' - 簡單。 '或直到停止' - 非常簡單:任務管理器/服務/停止服務。 – 2012-07-24 18:53:19

0

好吧,如果我要這樣做,並且間隔的約束不精確,並且我想絕對確保多個計時器事件永遠不會導致我的代碼重新進入,如果我的代碼偶爾花費的時間比間隔長,我會使用一個sleep()循環,讓事情沒有任何額外的計時器,只是增加了複雜度,似乎是一個簡單的要求。

除了必須處理消息的GUI線程(或者必須處理啓動/停止等的主要服務線程)之外,定時器通常是不恰當,笨拙的,或者如果另一個線程/池必須提高定時器事件,上下文切換。

無論如何,在Vista/W7上,通過停止產生睡眠線程的服務是沒有問題的。 OS需要大約20秒才能認識到,儘管服務主線程已經處理了停止消息,但服務進程仍然阻塞了線程 - 它終止了服務進程,從而終止了任何睡眠/運行/等待/任何線程。