c# – SQL Server使用超时请求做什么?
发布时间:2020-12-15 06:50:08 所属栏目:百科 来源:网络整理
导读:假设我使用C#来运行长时间运行的SQL Server存储过程(可以说30分钟).进一步假设我在C#中的查询中放置了1小时的超时时间,这样如果无论什么原因,SP需要比预期的更长的时间,我不会最终垄断DB.最后,假设这个存储过程有一个try / catch块来捕获错误,并做一些清理,
假设我使用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |