客户端数据库的连接挂起应用程序

时间:2013-12-17 11:15:43

标签: c# asp.net sql-server sqlconnection

在我的应用程序上,我需要连接客户端数据库(SqlServer),看看我们是否可以连接。 这些是来自web.config的连接字符串(值不是那样,我改了ip,用户和pwd)

<add name="ConnectionStringLibracom" connectionString="Data Source=192.168.1.45\SqlServer2008;Initial Catalog=xxx;user=xxx;pwd=xxx;Application Name=MES"
      providerName="System.Data.SqlClient" /> (MINE)
<add name="ConnectionStringMigplus" connectionString="Data Source=999.99.999.99;Initial Catalog=xxx;user=xxx;pwd=xxx"
          providerName="System.Data.SqlClient" /> (CLIENT)

但是这段代码挂起了我的整个应用程序(当我说它挂起时,我的意思是它不允许我的应用程序连接到我们的数据库)。我在Load事件的Default.aspx上执行它:

protected void Page_Load(object sender, EventArgs e)
{
    if (!TestaIntegracaoErpMigplus())
    {
        lblMensagemIntegracao.Visible = true;
        Session["Integracao"] = false;
    }
    else
        Session["Integracao"] = true;
}

protected static bool TestaIntegracaoErpMigplus()
{
    string connectionStringMigplus = WebConfigurationManager.ConnectionStrings["ConnectionStringMigplus"].ConnectionString;
    bool ret = false;

    using (SqlConnection Conn = new SqlConnection(connectionStringMigplus))
    {
        try
        {
            Conn.Open();
            if (Conn.State == ConnectionState.Open)
            {
                ret = true;
            }
        }
        catch (SqlException)
        {
            ret = false;
        }
    }

    return ret;
}

@EDIT:问题不在于我是否可以连接到服务器,问题是:当我尝试连接到该数据库时,我的asp.net网站冻结到其他页面的新请求

2 个答案:

答案 0 :(得分:5)

您无需检查ConnectionState

如果无法打开连接an exception is throw

可能此检查导致您的问题

protected static bool TestaIntegracaoErpMigplus()
{
    bool ret = true;    

    try
    {
        string connectionStringMigplus = WebConfigurationManager.ConnectionStrings["ConnectionStringMigplus"].ConnectionString; 
        using (SqlConnection Conn = new SqlConnection(connectionStringMigplus))
        {
            Conn.Open();
        }
    }
    catch (Exception)
    {
        ret = false;
    }
    return ret;
}

------------- UPDATE ------------------

尝试降低连接字符串中的connection timeout

<add name="ConnectionStringMigplus" connectionString="Data Source=999.99.999.99;Initial Catalog=xxx;user=xxx;pwd=xxx;Connection Timeout=5" providerName="System.Data.SqlClient" />

答案 1 :(得分:4)

您可以尝试将连接移至Task并使用Wait函数暂停,类似这样

protected static bool TestaIntegracaoErpMigplus()
{
    string connectionStringMigplus = WebConfigurationManager.ConnectionStrings["ConnectionStringMigplus"].ConnectionString;
    var task = Task.Factory.StartNew<bool>(()=>{
        bool ret = true;
        using (SqlConnection Conn = new SqlConnection(connectionStringMigplus))
        {
            try
            {
                Conn.Open();
            }
            catch (SqlException)
            {
                ret = false;
            }
        }

        return ret;
    });

    if(task.Wait(/*your timeout in milliseconds*/)){
        return task.Result;
    }

    return false;
}