如何在不使用 catch Exception 的情况下从 .NET 应用程序检测 SQL Server 超时
在我当前的应用程序中,我通过调用 T-SQL Update 命令来执行更新。问题是当同一条记录当时被其他用户锁定时。
在.NET应用程序中,应用程序将等待直到SQL Server超时,然后它将抛出SqlException超时。
是否可以首先检查特定记录是否被其他进程锁定,而不是捕获异常?
In my current application, i am performing an update by invoking T-SQL Update command. The problem is when the same record is locked by other users at that time.
At .NET application, the application will wait until SQL Server timeout, then it will throw the SqlException timeout.
Is it possible to perform a check first whether a particular record is locked by other process rather than catching the exception ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不是真的。
标准方法是使用
try/catch
并处理SqlException
Number1205
(死锁受害者),然后重试查询:[注意:break 语句为紧凑性而未添加
另请注意,通过提供适当的覆盖索引可以消除许多锁定问题。
您可以通过查询
sys.messages
:No, not really.
The standard way is to use
try/catch
and handleSqlException
Number1205
(deadlock victim), and retry your query:[Note: break statements not added for compactness
Also note, many locking issues can be eliminated by providing the appropriate covering indexes.
You can retrieve a complete list of SQL Server's error messages by querying
sys.messages
:您可以使用超时非常短的单独连接来尝试通过更新某些字段来锁定记录,但这仍然无法为您提供 100% 的可靠性。
如果您确实遇到多个用户编辑相同记录的情况,您应该考虑乐观锁定技术。
另外,请确保您根本不允许用户锁定记录 - 对任何更新使用断开连接模式。换句话说,锁定只会发生在更新的短时间(<100 ms)
You could use separate connection with very short timeout to attempt to lock the record by updating some field, but this is still not going to give you 100% reliability.
if you really have the situation with multiple users editing same records, you should look into optimistic locking techniques.
Also, make sure you do not allow users to lock the records at all - use disconnected mode for any updates. In other words, the locking will only occur for a short time of update (<100 ms)