作者:我是你的小pig的美丽家园 | 来源:互联网 | 2023-05-17 14:07
IhavethefollowingcodetotestDBconnection,itrunsperiodicallytotestforDBavailability:我
I have the following code to test DB connection, it runs periodically to test for DB availability:
我有以下代码测试DB连接,它定期运行以测试DB可用性:
private bool CheckDbConn()
{
SqlConnection cOnn= null;
bool result = true;
try
{
cOnn= DBConnection.getNewCon();
ConnectionState cOnState= conn.State;
if (cOnState== ConnectionState.Closed || cOnState== ConnectionState.Broken)
{
logger.Warn(LogTopicEnum.Agent, "Connection failed in DB connection test on CheckDBConnection");
return false;
}
}
catch (Exception ex)
{
logger.Warn(LogTopicEnum.Agent, "Error in DB connection test on CheckDBConnection", ex);
return false; // any error is considered as db connection error for now
}
finally
{
try
{
if (conn != null)
{
conn.Close();
}
}
catch (Exception ex)
{
logger.Warn(LogTopicEnum.Agent, "Error closing connection on CheckDBConnection", ex);
result = false;
}
}
return result;
}
And:
和:
static public SqlConnection getNewCon()
{
SqlConnection newCon = new SqlConnection();
newCon.COnnectionString= DBConnection.ConnectionString; // m_con.ConnectionString;
newCon.Open();
return newCon;
}
My question is: will this work as expected?
我的问题是:这能像预期的那样工作吗?
Specifically, I'm concerned aobut the test of the ConnectionState
. Is it possible that the state will be: connecting (since Open()
is synchronous)?
具体地说,我关心的是连接状态的测试。是否可能状态是:连接(因为Open()是同步的)?
What should I do in that case?
在那种情况下我该怎么办?
Thanks in advance, Omer
谢谢你提前,俄梅珥
6 个解决方案