2009-11-28 84 views
1

我想測試連接字符串是否正確,所以我創建了一個新的SqlConnection,稱爲Open()方法。但是,當連接字符串的server/data_source部分出錯時,它必須等待很長時間才能返回。如何限制SqlConnection.Open()的等待時間?

我試着給連接字符串添加連接超時,它沒有工作; 我試過在另一個線程中打開連接,然後幾秒鐘後調用Thread.Abort()。 他們都沒有工作。

那麼這樣做的正確方法是什麼? 謝謝。

回答

1

經過研究,我找到了解決方案(http://www.improve.dk/blog/2008/03/10/controlling-sqlconnection-timeouts),我修改了一下。如果沒有拋出異常,那麼連接字符串是有效的。

 var alive = true; 
     string error = null; 
     var success = false; 

     // ReSharper disable AccessToModifiedClosure 
     // ReSharper disable UseObjectOrCollectionInitializer 
     var thread = new Thread(() => 
            { 
             try 
             { 
              var connection = new SqlConnection(connectionString); 
              connection.Open(); 
              connection.Close(); 

              if (alive) 
               success = true; 
             } 
             catch (SqlException ex) 
             { 
              if (alive) 
               error = ex.Message; 
             } 
             catch (ThreadAbortException) 
             { 
             } 
             finally 
             { 
              if (connection.State == ConnectionState.Open) 
               connection.Close(); 
             } 
            }); 
     // ReSharper restore AccessToModifiedClosure 
     // ReSharper restore UseObjectOrCollectionInitializer 
     thread.IsBackground = true; 
     var sw = Stopwatch.StartNew(); 
     thread.Start(); 

     var timeout = TimeSpan.FromSeconds(3); 
     while (sw.Elapsed < timeout) 
      thread.Join(TimeSpan.FromMilliseconds(200)); 
     sw.Stop(); 

     if (!success) 
     { 
      alive = false; 
      throw new Exception(error ?? "Connection timeout, please check the connection string."); 
     }