c# – SQL Server使用超时请求做什么?

假设我使用C#来运行长时间运行的sql Server存储过程(可以说30分钟).进一步假设我在C#中的查询中放置了1小时的超时时间,这样如果无论什么原因,SP需要比预期的更长的时间,我不会最终垄断DB.最后,假设这个存储过程有一个try / catch块来捕获错误,并做一些清理,如果它内部的任何步骤失败.

一些代码(C#):

using (sqlCommand comm = new sqlCommand("longrunningstoredproc"))
{
    comm.Connection = conn;
    comm.CommandType = CommandType.StoredProcedure;
    comm.CommandTimeout = 3600;
    comm.ExecuteNonQuery();
}
/* Note: no transaction is used here,the transactions are inside the stored proc itself. */

T-sql(基本相当于以下):

BEGIN TRY
   -- initiailize by inserting some rows into a working table somewhere
   BEGIN TRANS
     -- do long running work
   COMMIT TRANS
   BEGIN TRANS
     -- do long running work
   COMMIT TRANS
   BEGIN TRANS
     -- do long running work
   COMMIT TRANS
   BEGIN TRANS
     -- do long running work
   COMMIT TRANS
   BEGIN TRANS
     -- do long running work
   COMMIT TRANS
   -- etc.

   -- remove the rows from the working table (and set another data point to success)
END TRY
BEGIN CATCH
   -- remove the rows from the working table (but don't set the other data point to success)
END CATCH

我的问题是,当命令从C#端超时时,sql Server会对查询做什么?它会调用SP的catch块,还是将其完全切断,以便我需要执行C#代码的清理?

解决方法

超时由ADO.NET强制执行. sql Server不知道这样的命令超时. .NET客户端将发送“注意”TDS命令.您可以使用sql Profiler观察此行为,因为它具有“注意”事件.

sql Server收到取消它将取消当前正在运行的查询(就像SSMS在按停止按钮时一样).它将中止批次(就像在SSMS中).这意味着不能运行catch代码.连接将保持活动.

根据我的经验,交易将立即回滚.我不认为这是有保证的.

TL; DR:ADO.NET中的超时行为与在SSMS(或称为sqlCommand.Cancel)中按下停止的行为相同.

这里是参考:http://blogs.msdn.com/b/psssql/archive/2008/07/23/how-it-works-attention-attention-or-should-i-say-cancel-the-query-and-be-sure-to-process-your-results.aspx

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...