C#应用程序在失败的SqlConnection期间挂起

时间:2015-11-02 05:09:41

标签: c# winforms user-interface hang sqlconnection

我正在构建一个连接到SQL Server和数据库的C#应用​​程序。在我的网络上,运行服务器的PC在我的路由器上有一个保留的IP。因此,如果SQLConnection失败,这是代码的一部分。代码如下:

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;

    }

如果SqlConnection的参数是OK,那么应用程序不会挂起,但如果不正确,应用程序就会生气。我正在用Windows C#编程。

我认为在连接失败时使用状态栏检查连接的过程中我必须使用Threads。所以。帮我!请!

1 个答案:

答案 0 :(得分:1)

如果您想检查连接,请尝试创建新的thread来执行:

//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();
}

然后你的程序不会挂起。