gpt4 book ai didi

c# - 事务 - 避免插入时发生冲突

转载 作者:搜寻专家 更新时间:2023-10-30 19:50:48 24 4
gpt4 key购买 nike

我在我的 asp.net 应用程序中使用 EF6,但我遇到了一个问题,这有点烦人,而且我似乎无法找到一个好的解决方案。

我的代码是这样的:

using (var scope = TransactionScopeUtil.RepeatableReadMaxTimeoutRequired())
{
bool hasConflict = await BookingService.HasConflictAsync(newBooking);
if (!hasConflict)
{
await BookingRepository.InsertAsync(newBooking);
return Json(AjaxPayload.Success());
}
else
{
return Json(AjaxPayload.Error());
}
}

// The transaction scope builder:
public static TransactionScope ReadCommittedMaxTimeoutRequired()
{
return new TransactionScope(TransactionScopeOption.Required, new TransactionOptions()
{

IsolationLevel = IsolationLevel.ReadCommitted,
Timeout = TransactionManager.MaximumTimeout
}, TransactionScopeAsyncFlowOption.Enabled);
}

问题是,如果两个客户端推送相同的预订时间,则应该注册冲突。其中一个调用应返回一条消息,表明时间段已被预订。但如果他们完全正确地击中服务器(在相同的 milis 中),则不会。两个预订都可以毫无问题地保存。

我可以通过做一个可序列化的硬核锁定作用域来解决这个问题,但我确信有更好的方法,我太盲目了,看不到它?

在这种情况下,最佳做法是什么?

最佳答案

if two clients push the same booking time, a conflict should be registered

如果我没理解错的话,您不想同时阻止两个预订。 (你告诉 Stefan 一个“ super 用户”可以强制一个。)你只是想注册一个冲突?

这很容易做到,但你必须使用数据库。至少,必须有某个真理的仲裁者,某个单一的地方,在那里只有一次和一次对事物状态的最终理解。通常,这是数据库。逻辑看起来是这样的

insert into T values (X, time, priority = 1) where X not in T
if rows_affected = 1
hurrah
else
while rows_affected < 1
priority = max(priority) + 1
insert into T values (X, time, priority) where (X, priority) not in T
register conflict, you are $priority in line

将其转换为 SQL 或您正在使用的任何内容,将 {X, time, priority} 作为参数传递,然后就完成了。

顺便说一句,如果有帮助的话,这种方法有一个名称:乐观并发。幸运的话,该术语可能会出现在您的环境的文档中。

关于c# - 事务 - 避免插入时发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com