[英]Working With Multiple Timers in C# Web Service
我试图在一小时内执行3个与数据库相关的操作。
1:每隔一分钟检查一次特定时间
2:每15分钟更新一次特定记录
3:每60分钟更新一次特定记录
直到15分钟,一切都还好...但是在15分钟内,两个计时器必须同时访问数据库。 这就是为什么它向我显示错误。 Connection is already Open
。 现在,在60分钟后,所有三个Timer都同时访问数据库,因此这就是为什么它将再次显示消息Connection is Already Open
。 60分钟后,一切正常,直到15分钟。但是接下来的15分钟将到来。 消息将再次可见,依此类推。 这是计时器
计时器1:
_Timer = new Timer();
this._Timer.Interval = 1000 * 60 * 1;
this._Timer.Elapsed += new System.Timers.ElapsedEventHandler(this._Timer_Tick);
_Timer.Enabled = true;
这是_Timer_Tick方法
CheckConnnectionStatus();
string cGroupQuery = "select value from settings where id=1 ";
try
{
sqlConnection.Open();
sqlCommand = new SqlCommand(cGroupQuery, sqlConnection);
sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.Read())
{
string value= sqlDataReader[0].ToString();
if (value== "True")
{
Library.WriteErrorLog("System State Done Successfully");
TakeSystemState();
UpdateSystemState();
}
}
}
catch (Exception exp)
{
Library.WriteErrorLog(exp.Message.ToString() + " | Exception in CheckPrayerTime");
}
finally
{
CheckConnnectionStatus();
}
计时器2:
_Timer02 = new Timer();
this._Timer02.Interval = 1000 * 60 * 15;
this._Timer02.Elapsed += new System.Timers.ElapsedEventHandler(this._Timer02_Tick);
_Timer02.Enabled = true;
计时器3:
_Timer03 = new Timer();
this._Timer03.Interval = 1000 * 60 * 60;
this._Timer03.Elapsed += new System.Timers.ElapsedEventHandler(this._Timer03_Tick);
_Timer03.Enabled = true;
谁能指导我在Web Service的Timer中执行这三个操作的最佳方法
我正在使用Sql Server 2008R2 Express Edition
谢谢
根据文档,如果连接已经打开,则SqlConnection.Open()
方法将引发InvalidOperationException
。 有关更多详细信息,请参见: https : //msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx
作为解决方案,您可以在每个Timer
事件处理程序方法中创建一个新的SqlConnection
对象,并在完成处理后将其Dispose()
。
好的做法是,将新创建的SqlConnection
对象放在using
语句中,以便即使抛出异常也将释放连接:
using (var conn = new SqlConnection())
{
conn.Open();
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.