大家好:)我有一个关于C#中的parralelism和ms-sql的问题
我有一个方法,可以查找特定对象的Db。如果它不存在,它将把它添加到Db中。不幸的是,它是用Parallel.ForEach完成的,所以我遇到了一些情况,使用线程A和B:
A: 查找代码为"xxx"的实体-结果:不存在B: 查找代码为"xxx"的实体-结果:不存在A: 将实体添加到数据库-结果确定B: 将实体添加到Db-result:"违反UNIQUE KEY约束(…)重复键值为"xxx"
我该怎么做才能避免这种情况?
如果没有这个重复的错误,你想在这里捕获
try{
//execute you insert in base
}catch(Exception ex){
// If your constraint is not respected, an error is thrown.
console.WriteLine("db error : "+ex.Message);
}
但是,这是暂时的,它是功能性的,但它很糟糕,它不合适。。。
为了获得正确的代码,您需要创建一个后台处理程序:
class Spooler{
public System.Collections.Generic.List<String> RequestList = new System.Collections.Generic.List<String>();
public Spooler(){
// Open you Database
// Start you thread will be verify if a request adding in the collection
SpoolThread = new Thread(new ThreadStart(SpoolerRunner));
SpoolThread.Start();
}
public createRequestDb(String DbRequest){
RequestList.Add(DbRequest);
}
private void SpoolerRunner()
{
while (true)
{
if (RequestList.Count() >= 1){
Foreach (String request in RequestList){
// Here, you want to verify your request, if args already exist
// And add request in Database
}
}
// Verify is request exist in the collection every 30 seconds..
Thread.Sleep(30000);
}
}
}
为什么要使用后台处理程序?
因为,当您在调用线程之前初始化后台处理程序时,您希望在每个threah中调用后台处理程序,并且,对于每个请求,您在集合中添加请求,后台处理程序将处理一个接一个。。。而不是在同一时间在每个不同的线程中。。。
编辑:这个后台处理程序是一个示例,用于在数据库中逐个插入字符串请求,您可以在中创建一个后台处理程序,其中包含所需对象的集合,并在数据库中插入(如果不存在)。。。这只是一个解决方案的示例,当你有很多线程时,一个接一个的处理^^