ADO.NET:更快的方法来检查,如果数据库服务器可以访问? [英] ADO.NET: Faster way to check if the database server is accessible?
问题描述
目前,我用这code,检查数据库访问:
At the moment I am using this code to check if the database is accessible:
public bool IsDatabaseOnline(string con)
{
bool isConnected = false;
SQLConnection connect = null;
try {
connect = new SQLConnection(con);
connect.Open();
isConnected = true;
} catch (Exception e) {
isConnected = false;
} finally {
if (connect != null)
connect.Close();
}
return isConnected;
}
虽然这code正常工作,有一个缺点。如果服务器不在线也花费大约4个整体秒试图打开决定,这是以前无法获得的连接。
While this code works fine, there is a disadvantage. If the server is not online it spends about 4 full seconds trying to open the connection before deciding that it is not available.
有没有一种方法来测试,但不尝试实际打开它,并等待超时的连接?就像一个数据库,相当于平?
Is there a way to test the connection without trying to actually opening it and waiting for the timeout? Something like a database-equivalent of ping?
推荐答案
您可以只更改连接超时时间更短。做一些测试,看看你可以再低,仍然是可靠的。我敢打赌,你可以得到接近500毫秒。
You could just change the connection timeout to be shorter. Do some testing and see how low you can go and still be reliable. I bet you could get close to 500ms.
<一个href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx
这篇关于ADO.NET:更快的方法来检查,如果数据库服务器可以访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!