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

C# App hangs during failed SqlConnection

我正在构建一个连接到 SQL 服务器和数据库的 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的参数没有问题,应用不会挂,如果不正确,应用会卡。我正在使用 windows 形式的 C# 进行编程。

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

如果您想检查您的连接,请尝试创建一个新的 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();
}

那你的程序就不会挂了。