当我尝试执行以下代码时,程序无限期挂起。我不知道为什么,似乎还有其他关于这个问题的未回答的话题。虽然,如果无法访问 IP\网站,那么它会按预期工作。
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");
}
}
例如,如果我将连接字符串设置为
connectionString = "Data Source=www.nonexistentsite.com;Connection Timeout=5";
那么它会抛出一个异常。如何让它为活动站点抛出异常?...显然,谷歌也只是出于测试目的。
编辑 :
如果我尝试连接到无法访问的服务器名称或 IP 地址,我将收到此异常...
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)
更新 :
让程序运行一段时间后,它通常会在 3-5 分钟后最终超时,并给我上面发布的错误。我怎样才能让它更快地超时?