1

It is a .Net application which works with an external device. When some entity (corresponds to the row in a table) wants to communicate with device, the corresponding row in the SQL Server table should be locked until the device return a result or SQL Server times out.

I need to:

  • lock a specific row in a table so that row could be read, but could not be deleted or updated.
  • locking mechanism should run in a separate thread so that application's main thread works as usual
  • lock should be released if a response has made
  • lock should be released after a while if no response is received

What is the best practice?

Is there any standardize way to accomplish this?

Should I:

  • run a new thread (task) in my C# code and begin a serializable transaction, select desired row transactionally and wait to either time is up or cancellation token is received?

  • or use some combination of sp_getapplock and ...etc?

4

2 回答 2

1

您不能跨事务或会话对锁进行操作。这种方法是不可行的。

您需要运行一个事务并在您希望锁持续存在的时间内保持打开状态。

您使用的并行技术是无关紧要的。具有异步 ADO.NET IO 的异步方法将是合适的。所以将是一项单独的LongRunning任务。

您可能需要将 a 传递CancellationToken给事务代码,该代码在发出信号时会使事务关闭。这样您就可以实现任意关闭条件,而不会弄乱事务代码。

于 2015-08-29T11:29:32.963 回答
1

以下是您应该考虑的几点:

  • Sp_getapplock 不是基于行的,所以我认为它不是你可以使用的东西
  • “应用程序的主线程照常工作。” ——但是如果你锁定行,任何更新/删除操作都会卡住,那么它像往常一样工作吗?
  • 锁定结束后,是否可以在被阻止之后立即进行所有更新?
  • 您的阻止线程是否也会进行更新?
  • 如果应用程序和外部设备正在进行更新,如何确保以正确的顺序/方式处理它们?

我想说您需要设计您的应用程序以在这种情况下正常工作,而不仅仅是尝试将这种功能添加为附加组件。

标题说的是在另一笔交易中发布,但这并没有在问题中真正解释。

于 2015-08-29T07:59:58.733 回答