[英]Changing Connection Timeout for SQL Server connection has no effect
我正在嘗試使用以下代碼設置與C#中的SQL服務器連接的超時:
var sscsb = new SqlConnectionStringBuilder(sConn);
sscsb.ConnectTimeout = 10;
SqlConnection connection = new SqlConnection(sscsb.ConnectionString);
using (connection)
{
connection.Open();
connection.Close();
return (true);
}
但是在connection.Open()
語句拋出錯誤之前經過了30秒。 如何將連接超時設置為較短的值?
當我嘗試連接到無效的服務器名稱,或者當有效服務器的網絡連接斷開時,我遇到了這個問題。 在這些情況下,超時值被忽略。 似乎超時不適用於驗證服務器並發送連接請求的嘗試。 它似乎只適用於找到有效服務器並發出請求后等待連接的時間。
我使用了基於計時器的解決方案,雖然我似乎無法找到它,但它絕對是一種解決方法。 這種基於線程的解決方案似乎是要走的路。
我曾經調查過這個問題並得出這樣的結論:在連接字符串或連接中指定的連接超時意味着:如果sql服務器正在偵聽,請等待x秒以使其接受連接請求。 如果沒有服務器正在偵聽端口(例如,sql server未運行),則使用默認套接字連接超時,默認為30秒。 解決方法是使用自定義超時手動打開與sql server的套接字連接,以檢查它是否正在運行。
下面的代碼測試連接並能夠在連接上運行查詢。 查詢需要引用目標D / B中的小表:
/// <summary>
/// Return true if successful SQL connection
/// </summary>
/// <param name="conn"></param>
/// <param name="timeout">timeout in msec</param>
/// <returns></returns>
public static bool QuickSQLConnectionTest(SqlConnection conn, int timeout)
{
// We'll use a Stopwatch here for simplicity. A comparison to a stored DateTime.Now value could also be used
Stopwatch sw = new Stopwatch();
bool connectSuccess = false;
// Try to open the connection, if anything goes wrong, make sure we set connectSuccess = false
Thread t = new Thread(delegate()
{
try
{
sw.Start();
conn.Open();
SqlCommand cmd = new SqlCommand("Select Count(*) from Configuration", conn);
cmd.CommandTimeout = timeout/1000; // set command timeout to same as stopwatch period
cmd.ExecuteScalar();
connectSuccess = true;
}
catch (Exception Ex)
{
}
});
// Make sure it's marked as a background thread so it'll get cleaned up automatically
t.IsBackground = true;
t.Start();
// Keep trying to join the thread until we either succeed or the timeout value has been exceeded
while (timeout > sw.ElapsedMilliseconds)
if (t.Join(1))
break;
// If we didn't connect successfully
if (!connectSuccess)
{
return false;
}
else
{
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.