I have implemented SqlClient
connecting function with timeout parameter. It means, that connection.open()
is in another thread and after thread is started, I'm checking elapsed time. If the time had reached timeout, thread is aborted and no connection is established.
The thing is, that if I have timeout bigger then default connection.open()
timeout, open()
throws SqlException
, which isn't caught in my Catch(SqlException)
block.
I'm starting whole connecting process in another thread:
public void connect()
{
Thread connectThread = new Thread(waitForTimeout);
connectThread.Start();
}
Connecting thread -> starts another thread for timeout waiting
public void waitForTimeout()
{
connection = new SqlConnection(connectString);
Thread timeoutThread = new Thread(openConnection);
timeoutThread.Start();
DateTime quitTime = DateTime.Now.AddMilliseconds(timeout);
while (DateTime.Now < quitTime)
{
if (connection.State == ConnectionState.Open)
{
transac = connection.BeginTransaction();
command = connection.CreateCommand();
command.Transaction = transac;
break;
}
}
if (connection.State != ConnectionState.Open)
timeoutThread.Interrupt();
}
Here exception isn't caught after open() default timeout:
private void openConnection()
{
try
{
connection.Open();
}
catch(SqlException ex)
{
// This isn't caught anytime
}
}
Thank you for any ideas!
After comments I tried to implement new solution, and here it is:
Constructor:
/* ------------------------------------------------------------------------- */
public Database(string source, string database, string user, string password,
int timeout, DelegateConnectionResult connectResult)
{
this.timeout = timeout;
this.connectResult = connectResult;
connectString = "server=" + source +
";database=" + database +
";uid=" + user +
";pwd=" + password +
";connect timeout=" + Convert.ToInt16(timeout / 1000);
}
Asynchonous connect:
/* ------------------------------------------------------------------------- */
public void connectAsync()
{
connectThread = new Thread(connectSync);
connectThread.Start();
}
Synchronous connect:
/* ------------------------------------------------------------------------- */
public void connectSync()
{
connection = new SqlConnection(connectString);
try
{
connection.Open();
transac = connection.BeginTransaction();
command = connection.CreateCommand();
command.Transaction = transac;
if (connection.State == ConnectionState.Open)
connectResult(true);
else
connectResult(false);
}
catch
{
connectResult(false);
}
}
And I found the solution for original problem witch SqlException from this post: it has something to do with Exceptions settings in debugger of Visual Studio. If I unchecked "throw" choice at SqlException in Exceptions list (CTRL + D + E in Visual Studio), I'm finally able to catch exception.