I am building an C# app that connects to SQL Server and a database. On my network the PC that is running the server has a reserved IP on my router. So, this is the part of the code that hangs if SQLConnection fails. Here the code:
public static Boolean RevisarEstado(String ip, String usuario, String pass)
{
Boolean estado = false;
SqlConnection miconexion = new SqlConnection("Data source=" + ip + ";DataBase=Final_Algoritmos;User ID=" + usuario + ";Password=" + pass);
try
{
miconexion.Open();
estado = true;
miconexion.Close();
}
catch (Exception) { estado = false; miconexion.Close(); }
return estado;
}
if the parameters of SqlConnection are Ok, the app does not hangs, but if are not correct, the app hags. I am programming with windows form C#.
I think that I must use Threads during the process of checking the connection, using a status bar while the connection fails. So. Help me! Please!
If you want to check your connection, try creating a new thread to do:
//Put these two lines to where you want to check the connection
Thread checkConnection = new Thread(() => checkConn());
checkConnection.Start();
//Then create a method like below
public void checkConn()
{
//Call the check connection method here
if(!miconexion(ip, user, pass))
{
//Handle failure here, please use Invoke if you want to control the UI thread.
}
//For best resource usage, join the thread after using it.
Thead.Join();
}
Then your program won't hangs.