Linq-to-Sql 读取-测试-写入作为一项操作
我有 Tasks
表:Id (PK)、TaskName、Status
状态为以下之一:已排队、忙碌、完成。
我想使用多个线程来处理任务,为此我需要能够在一个操作中完成:
var task = db.Tasks.FirstOrDefault(t=>t.Status == (byte) TaskStatus.Queued);
task.Status = (byte) TaskStatus.Busy;
db.SubmitChanges();
显然,如果操作不是原子的,我可能会遇到并发问题。使用 Linq-to-Sql 执行上述操作的预期方法是什么(如果存在)?
我知道我可以用 1) storproc 或 2) db.ExecuteCommand("...")
或 3) 处理冲突 with try/catch
- 但我想确定没有更好的方法。
我知道这是一个非常基本的问题,但我无法找到明确的答案。
I have Tasks
table: Id (PK), TaskName, Status
Status is one of: Queued, Busy, Complete.
I want to use multiple threads to process the tasks, and for that I need to be able to do in one operation:
var task = db.Tasks.FirstOrDefault(t=>t.Status == (byte) TaskStatus.Queued);
task.Status = (byte) TaskStatus.Busy;
db.SubmitChanges();
Obviously if operation is not atomic I can get concurrency issues. What is (if one exists) an intended way to do the above using Linq-to-Sql?
I know I can do that with 1) storproc or 2) db.ExecuteCommand("...")
or 3) handle the conflict with try/catch
- but I want to be sure there is no a better way.
I know it is a very basic question, but I wasn't able to find a definite answer to this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想确保这在数据库中以原子方式发生(无论哪个线程或应用程序调用它),您可能应该在存储过程中执行此操作并在适当的级别锁定。存储过程应该检索并更新记录,然后释放并返回它(确认!我不是指 TSQL
return
语句,但你知道我的意思是select
它,我信任!)因此,L2S 只需调用存储过程并返回一个要处理的任务,该任务已设置为“Busy”。 L2S 既不知道(也不关心)锁定什么/如何锁定 - 因此不会使问题复杂化并带来更多死锁的机会。
If you are wanting to be sure that this is happening atomically in the database (regardless of what thread or application is calling it), you probably should do it in a sproc and lock at an appropriate level there. The sproc should retrieve and update the record, then release and return it (Ack! I don't mean the TSQL
return
statement, but you know I meanselect
it, I trust!)So L2S just calls the sproc and gets back a task to work on, already set as
Busy
. L2S neither knows (nor cares) what/how things were locked - and therefore can not complicate matters and introduce more chances for deadlocks.