破坏长时间运行的存储过程的最佳方法是什么?
中断长时间运行的存储过程(最多 20 分钟)的最佳方法是什么? 存储过程内部封装在事务中。如果我关闭连接,该事务会回滚吗? 另一种方法是在启动存储过程之前在 C# 中启动事务,当我想取消存储过程时,我只需要回滚 C# 事务。
What is the best approach of breaking long running stored procedures (up to 20 minutes)?
Inside the Stored procedure is wrapped in a transaction. If I close connection will this transaction be rolled back?
Another approach is to start a transaction in C# before I start the stored procedure and when I want to cancel the stored procedure I just need to rollback the C# transaction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果关闭连接,并且在事务提交之前 SQL Server 发现连接断开,则 SQL Server 将回滚事务。将会有一个(非常)小的时间窗口,当您断开连接时事务可能会完成。
自定义事务会增加复杂性,并且对于单个存储过程调用来说几乎没有什么好处。所以我会选择断开连接。
If you close the connection, SQL Server will rollback the transaction if it notices the disconnect before the transaction commits. There'll be a (very) small time window where the transaction might complete just when you disconnect.
A custom transaction adds complexity and has few benefits for a single stored procedure call. So I'd go for the disconnect.
您可以在三个地方设置超时:连接、命令以及页面超时(如果您最终要对网页进行编程)。
本例中的相关超时是命令超时。
更新:通过用户事件取消:
要通过用户事件取消命令,请对该命令调用 Cancel()。我还没有编写代码来测试这一点,但我怀疑一旦您调用 ExecuteReader() 它就会阻塞,因此您需要一个异步调用 - BeginExecuteNonQuery(),这确实很难设置 - 它需要查询字符串上有额外的内容,我认为它需要 SQL2005+
UPDATE:回复:事务
C#(或 ADO.NET)事务代码添加了大约两行代码,并保证存储过程(其中可能有多个语句,不是今天,也许是一年后)的调用作为一个单元成功或失败。它们通常不是性能不佳的根源,但在不使用时可能会成为性能不佳的根源——例如,一长串插入在事务中运行得更快。
如果不调用 CommitTrans() 事务将会回滚,您不必显式调用 Rollback()
You can set a time out in three place-- the connection, the command, and if you are ultimately programming a web page-- in the page time out.
The relevant time out in this case is the command time out.
Update: Cancelling by a user's event:
To cancel your command by a user event, call Cancel() on the command. I haven't written code to test this, but I suspect that once you call ExecuteReader() it will block, so you'd need an async call-- BeginExecuteNonQuery(), which really is a pain to set up-- it requires extra things on the query string and I think it requires SQL2005+
UPDATE: Re: Transactions
C# (or ADO.NET) transaction code adds about two lines of code and guarantees invocations of stored procedures (which may have more than one statement in them, in not today, maybe a year from now) succeed or fail as a unit. They normally are not a source of poor performance and can be a source of poor performance when not used-- e.g. a long series of inserts runs faster in a transaction.
If you do not call CommitTrans() the transaction will rollback, you do not have to explicitly call Rollback()
在开始事务时设置超时。
Set Timeout at the time of beginning the transaction.