Parallel.ForEach - 将对象添加到Db如果不存在

时间:2012-08-03 08:13:24

标签: multithreading c#-4.0 unique-constraint

嗨,大家好女孩:)我对C#

中的parralelism和ms sql有疑问

我有查看特定对象的Db的方法。如果它不存在,它会将它添加到Db。不幸的是,它完成了Parallel.ForEach,所以我遇到了一些情况,使用线程A和B:

答:查找代码为'xxx'的实体 - 结果:不存在 B:查找代码为'xxx'的实体 - 结果:不存在 答:将实体添加到Db - 结果确定 B:向Db添加实体 - 结果:“违反UNIQUE KEY约束(...)重复键值为'xxx'”

我该怎么做才能避免这种情况?

1 个答案:

答案 0 :(得分:0)

如果没有这个重复的错误,你想要赶上

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中调用假脱机程序,并且,对于每个请求,您在集合中添加请求,并且假脱机程序将一个接一个地处理...并且不是在同一时间在每个不同的线程......

修改 这个假脱机程序是一个示例,用于在数据库中逐个插入字符串请求, 你可以创建一个带有你想要的对象集合的假脱机程序,如果不存在则插入db ...这只是一个解决方案的示例,当你有很多线程时,一个接一个地进行处理^^