我开发了一个多线程应用程序,它在数据库中插入一些数据。 假设我有以下情况:
public void Foo()
{
Task.Factory.StartNew(() => AddTeams());
Task.Factory.StartNew(() => AddTable());
}
如您所见,我调用了两种不同的方法将数据插入数据库,问题是每种方法都需要检查特定表中是否存在特定记录:
public void AddTeams()
{
//Pseudo code:
//Check if a team with id 1249 exist in the table team
//if not exist in the table team, insert the team with id 1249
//then insert the record attached with an `FK` to the team table.
}
同样的事情发生在 AddTable
上,所以有时我会得到这个错误:
'Duplicate entry '1249' for key 'PRIMARY
因为AddTable
方法检查失败,失败的原因是我使用的并行化,总结:时间问题。
我该如何管理?
我想到的唯一方法是处理异常,但我不喜欢这种方法。
最佳答案
您只需不并行化查询即可获取团队并在必要时创建团队。你不想也不需要做两次,开始时只需要做一次。因此,获取或创建团队,获取该团队的主键,然后将其传递给这两个方法以分别创建一个相关对象,这可以并行完成。
关于c# - 如何防止使用多线程插入重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50489356/