Every time I had problem with my SQL Server connection (ex. someone switch of server) my application will show an exception message in a messagebox. I don't know when will the connection available except I keep trying to open the connection / execute a query.
So I create a wait form that will appear if connection is unavailable, keep trying to open the connection, and close itself when connection is available again.
To hide the freeze from user, I use a background worker.
This is the background worker code
private void StartLoader(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 10; i++)
{
if (this.par.sqSuccess) //if no error, means connection is available, stop looping
{
break;
}
else
{
i -= 1;
}
System.Threading.Thread.Sleep(5000); //report progress every 5 second
}
This is the background worker's progress changed event
this.cnn = new SqlConnection(this.par.Constr);
try
{
this.cnn.Open(); //SqlConnection
this.par.sqSuccess = true; //if no error, then I change this variable
}
catch (Exception ex)
{
this.par.Exception = ex.Message;
}
finally
{
if (this.cnn != null) { this.cnn.Dispose(); }
}
if (this.par.sqSuccess) { this.Close(); }
After everything is complete, I tried to stop SQL Server service from services.msc
, then I try to connect.
The wait form will appear and keep doing its job.
A few second after I try to connect, I start the service again and the wait form did close, success.
This is the problem, when I wait a little bit longer before I start the service again, the wait form still closed, but it takes a while.
After I check everything, it seems like the cnn.open()
queue up and the longer I stop the service, the longer it takes for the wait form to close.
I searched google and try to add Connect Timeout=3; behind my connection string, as I'm sure my thread.sleep(5000) won't make them queue up, but still not working.
Someone told me to use cnn.OpenAsync();
After reading the documentation about OpenAsync
, this is what I do.
static async Task<ConnectionState> Method(SqlConnection cnn)
{
await cnn.OpenAsync();
return cnn.State;
}
And this
private void SQLClientLoader_Load(object sender, EventArgs e)
{
do
{
this.cnn = new SqlConnection(this.par.Constr);
try
{
ConnectionState cst = Method(cnn).Result;
if (cst == ConnectionState.Open)
{
this.par.sqSuccess = true;
}
else
{
}
}
catch (Exception ex)
{
this.par.sqSuccess = false;
this.par.Exception = ex.Message;
}
finally
{
}
} while ((bool)this.par.sqSuccess != true);
}
The code above freezes my application every time the form load code executed.
I need simple instruction of how to wait for the cnn.Open
process to finish or to cancel it if it takes too long.
Thank you in advance