pax*_*cow 7 c# multithreading loops
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));
}
Run Code Online (Sandbox Code Playgroud)
我怎么能让这个循环在5秒钟内运行一次或直到停止.
mel*_*okb 16
最简单的方法是:
while (true) {
// code here
Thread.Sleep(5000);
}
Run Code Online (Sandbox Code Playgroud)
但是,为了更强大,我建议使用适当的计时器的Windows服务.
尝试:
while(true)
{
try
{
thread.sleep(5000)
}
catch(Exception e)
{
//handle the exception
}
}
Run Code Online (Sandbox Code Playgroud)
它最简单.
我会包装你的代码并使用一个计时器对象,它允许你控制计时器本身(停止,启动等)
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
}
Run Code Online (Sandbox Code Playgroud)
更多信息
http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.100%29.aspx