sqlconnection.open ()의 대기 시간을 제한하는 방법?
-
06-07-2019 - |
문제
연결 문자열이 올바른지 테스트하고 싶습니다. 따라서 Open () 메소드라는 새 SQLConnection을 만들었습니다. 그러나 Connection String의 Server/DateSource 부분이 잘못되면 돌아 오기 전에 오랫동안 기다려야합니다.
연결 문자열에 연결 시간 초과를 추가하려고 시도했지만 작동하지 않았습니다. 다른 스레드에서 연결을 열어 보았을 때 몇 초 후에 Thread.Abort ()를 호출했습니다. 그들 중 누구도 작동하지 않았습니다.
그렇다면 이것을하는 올바른 방법은 무엇입니까? 감사.
해결책
연구 후, 나는 해결책을 찾았다 ( 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.");
}
제휴하지 않습니다 StackOverflow