Connection.open for hangs indefinitely, no exception is thrown

TheKobra picture TheKobra · May 8, 2013 · Viewed 9.4k times · Source

When I try to do the following code, the program hangs indefinitely. I don't know why and there seems to be other unanswered topics on the matter. Although, if the IP\website cannot be reached, then it works as intended.

    private void DoStuff()
    {
        string connectionString = "Data Source=www.google.com;Connection Timeout=5";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open(); //Hangs here indefinitely
            Console.WriteLine("Test");
        }
    }

For example, if I set the connection string to

connectionString = "Data Source=www.nonexistentsite.com;Connection Timeout=5";

then it will throw an exception. How do I get it to throw an exception for an active site? ... Also google is just for testing purposes, obviously.

EDIT :

If I try to connect to an unreachable server name or IP address I WILL get this exception...

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

UPDATE :

After letting the program run for quite a while, it usually times out finally after 3-5 minutes and gives me the error I posted above. How can I get it to timeout quicker?

Answer

Darin Dimitrov picture Darin Dimitrov · May 8, 2013

If you have set an FQDN (Fully Qualified Domain Name) for your Data Source such as example.com and the DNS server is unable to resolve this FQDN for a long time it is pretty obvious that your request will hang out. Make sure that the machine from which you are running your application can reach the SQL server and resolve it without any issues. Also you probably want to make sure that there is no firewall that might be blocking the request.

Another possible cause for those symptoms is if you have exhausted the connection pool of ADO.NET. This could happen if you have many slow SQL queries running in parallel, each of them taking a physical connection to the database. There is a limit in the number of available connections on this pool and when this limit is reached the next call to connection.Open() might wait for an available connection to be returned to the pool.

Remark: you might also need to specify in your connection string how you want to authenticate against the SQL server. Checkout connectionstrings.com for more examples.

All this is to say that there is absolutely nothing wrong in the C# code you have posted in your question. It looks more like a network related problem that you could bring to the attention of your network administrators.