我有一个运行一些ExecuteNonQuery
命令的循环。有时它会返回错误消息:
ExecuteNonQuery requires an open and available connection. The connections
current state is closed.
这是我的代码:
private void MyTimerEventHandler(object src, ElapsedEventArgs a)
{
sqlCon = new SqlConnection("server=" + appConfig.sqlServer + ";Trusted_Connection=yes;database=testdb;connection timeout=30;");
sqlCon.Open();
foreach (TagManager tm in tagManagerList)
{
foreach (Tag tag in tm.getTags())
{
SqlCommand insCmd = new SqlCommand("INSERT INTO tag_values (tag_id, value, time) Values (@tagId, @tagValue, @tagTime);", sqlCon);
insCmd.Parameters.Add(new SqlParameter("@tagId", tag.tagNameId));
insCmd.Parameters.Add(new SqlParameter("@tagValue", tag.value));
insCmd.Parameters.Add(new SqlParameter("@tagTime", tag.time));
insCmd.ExecuteNonQuery();
}
}
sqlCon.Close();
}
Timer
此代码在每 15 秒运行一次的事件处理程序中执行。GC.KeepAlive()
如果这有什么不同,计时器就会保持活动状态。