微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/94463.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐