简体   繁体   中英

SqlException takes too long to appear

I am testing a method to change the connection string of my app.config file, and then check if the connection is correct.

The problem is that, when the connection string is invalid or the server isn´t found, it takes around 10 seconds to fire the exception.

Is this normal?

My project consist in a windows form application, in C# and SQL server express. The server is in a local machine inside my local net. I have tried the same code in the server computer, and the delay is the same.

private void boton1_Click(object sender, EventArgs e)
    {
        using(SqlConnection con=new SqlConnection(connectionStringsSection.ConnectionStrings["Default"].ConnectionString))
        {
            con.Open();
        }
    }

As outlined in the C# docs for SqlConnectionStringBuilder , the connection timeout is something that is configurable to your particular need. Per their sample code on my local machine, it would appear the default timeout is 15 seconds, but you can set it as needed. Maybe in your use case, a timeout of 1 second would be fine, since you know the connection is local, and longer waits are unnecessary. However, any external connection should have a more generous timeout window to allow for routing issues, server load, etc.

The SqlConnectionStringBuilder class has many attributes that could help in this regard, but I've outlined the ones specific to your situation below:

var csb = new SqlConnectionStringBuilder
{
    ConnectionString = connectionStringsSection.ConnectionStrings["Default"].ConnectionString,
    ConnectRetryCount = 0,
    ConnectRetryInterval = 0,
    ConnectTimeout = 0
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM