博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
控制连接超时
阅读量:4686 次
发布时间:2019-06-09

本文共 1596 字,大约阅读时间需要 5 分钟。

首先连接超时分为三种,

TCP Connection to SQL Server -> SqlConnection.Open -> SqlCommand.Execute
先说第二种超时,sqlcon打开,我们不能直接设置connectiontimeout,只能在连接字符串中设置:
Data Source=server;Initial Catalog=databaseUser Id=username;Password=password;Connect Timeout=3
此设置默认时间为妙,而不是毫秒。默认是三十秒,可以设置为3秒。
注意:此处不能设置conn.open()超时回应的时间。因为conn.open(),不只是sqlserver响应尝试连接数据库的时间,其中还有Tcp请求的时间.所以如果
你设置Connect Timeout=2,在连接不到server的情况下,报告超时的时间也远远超过2s。因为此处设置的只是在sqlserver必须回应一个连接
尝试的时间。但是如果你根本就无法连接到server,这个设置也就无从谈起。

第三种超时比较简单,就是sql语句在数据库中的执行时间。通过 SqlCommand.CommandTimeout就可以进行设置。

第一种超时就是tcp请求的超时,这个是没有办法通过设置属性实现的。但是我们必须要控制它,因为一个连接可能几十秒之后才会回应你超时

了,这是难以忍受的。

下面是一个例子:

public static class SqlExtensions
{
public static void QuickOpen(this SqlConnection conn, int timeout)
{
// We'll use a Stopwatch here for simplicity. A comparison to a stored DateTime.Now value could also be used
Stopwatch sw = new Stopwatch();
bool connectSuccess = false;
// Try to open the connection, if anything goes wrong, make sure we set connectSuccess = false
Thread t = new Thread(delegate()
{
try
{
sw.Start();
conn.Open();
connectSuccess = true;
}
catch { }
});
// Make sure it's marked as a background thread so it'll get cleaned up automatically
t.IsBackground = true;
t.Start();
// Keep trying to join the thread until we either succeed or the timeout value has been exceeded
while (timeout > sw.ElapsedMilliseconds)
if (t.Join(1))
break;
// If we didn't connect successfully, throw an exception
if (!connectSuccess)
throw new Exception("Timed out while trying to connect.");
}
}

参考链接:

转载于:https://www.cnblogs.com/Glowd/archive/2012/09/13/sqlconntimeout.html

你可能感兴趣的文章
使用 Windows Vista 的凭据提供程序创造自定义的登录体验
查看>>
Coding之路——重新学习C++(9):解决异常
查看>>
[大话数据结构-读书笔记] 算法
查看>>
打开和写入word文档
查看>>
Tips
查看>>
极客时间_Vue开发实战_05.Vue组件的核心概念(1):属性
查看>>
阶段1 语言基础+高级_1-3-Java语言高级_02-继承与多态_第7节 内部类_17_接口作为方法的参数和或返回值...
查看>>
SQL Server 权限管理
查看>>
ajax.net updatepanel 中数据量过大导致 500 错误
查看>>
Saiku部分函数解析(八)
查看>>
Hdu 2100 Lovekey 模拟大数相加<进位转换..>
查看>>
html标签pre在php调试中使用技巧
查看>>
简单的下路由(我们可以在控制器中看到路由参数)
查看>>
springmvc 加载静态文件失败
查看>>
Oracle 系统表大全
查看>>
微信个人公众号推广
查看>>
hdu 4081 次小生成树
查看>>
springboot 整合 mybatis,thymeleaf
查看>>
SQL Server 同步复制中的MSSQL_REPL-2147201001問題處理
查看>>
HDOJ 动态规划总结
查看>>