我有一个窗口,我在其中的 OnStart() 方法中添加了一个无限循环。我已经对该服务进行了 1 小时的测试,它运行良好。但因为这是我的第一个 Windows 服务
所以怀疑无限循环的性能。
这是代码..
protected override void OnStart(string[] args)
{
while(true){
string Query="";
Query = "SELECT * FROM 'reportsetting` order by SendingTime;";
MySqlConnection con = new MySqlConnection(conn);
MySqlCommand comm = new MySqlCommand(Query, con);
con.Open();
MySqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
time = dr["SendingTime"].ToString();
if ((str = DateTime.Now.ToString("HH:mm")).Equals(time))
{
//Execute Function and send reports based on the data from the database.
Thread thread = new Thread(sendReports);
thread.Start();
}
}
//Halt for this Moment
while ((str = DateTime.Now.ToString("HH:mm")).Equals(time))
{
}
}
}
public void sendReports() {
}
所以想知道它是否可以长期运行。谢谢..
最佳答案
每 40 秒重新运行一次查询:
private const string Query = "SELECT * FROM 'reportsetting` order by SendingTime;"
protected override void OnStart(string[] args)
{
_timer = new Timer(40 * 1000); // every 40 seconds
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start(); // <- important
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MySqlConnection con = new MySqlConnection(conn);
MySqlCommand comm = new MySqlCommand(Query, con);
con.Open();
MySqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
time = dr["SendingTime"].ToString();
if ((str = DateTime.Now.ToString("HH:mm")).Equals(time))
{
//Execute Function and send reports based on the data from the database.
Thread thread = new Thread(sendReports);
thread.Start();
}
}
}
类似的东西。 正如 Groo 所提到的,您可能希望每次都处理连接,这样您就不会在内存中徘徊。
关于c# - Windows 服务中的无限 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25580630/