[英]Ensuring release of pessimistic lock
I'm considering implementing the pessimistic locking pattern in a WinForms insurance quoting application using SQL Server. 我正在考虑使用SQL Server在WinForms保险报价应用程序中实现悲观锁定模式。 Before a user starts working on a quote, a record will be added to the lock table;
在用户开始处理报价之前,一条记录将被添加到锁表中。 when they're done, the record will be deleted from the table.
完成后,记录将从表中删除。
My question is, how do I ensure that the lock is released in the event of a failure which is outside of my application's control? 我的问题是,如何确保在应用程序无法控制的故障情况下释放锁定? I'm thinking mostly of client side network connection errors or power failures, but there are endless possibilities.
我主要考虑的是客户端网络连接错误或电源故障,但是有无穷的可能性。
Rather than a locking table, consider a session level application lock ( https://msdn.microsoft.com/en-us/library/ms189823.aspx ). 而不是锁定表,请考虑会话级应用程序锁定( https://msdn.microsoft.com/zh-cn/library/ms189823.aspx )。 The lock will be released when the SQL session is terminated for any reason, or when released explicitly.
当SQL会话由于任何原因终止或明确释放时,将释放该锁。
--acquire lock
DECLARE
@ReturnCode int
, @ClientID nvarchar(255) = '12345';
EXEC @ReturnCode = sp_getapplock
@Resource = @ClientID
, @LockMode = N'Exclusive'
, @LockOwner = 'Session'
, @LockTimeout = 0;
IF @ReturnCode < 0
BEGIN
RAISERROR('Lock for quote not be granted for ClientID %s. Return code=%d', 16, 1, @ClientID, @ReturnCode);
END;
--release lock
DECLARE
@ReturnCode int
, @ClientID nvarchar(255) = '12345';
EXEC @ReturnCode = sp_releaseapplock
@Resource = @ClientID
, @LockOwner = 'Session';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.