Creating the records follows a simple flow: check if there is no similar record in the DB, and if not, create a record. The seriesInstUid is not the primary key. The primary key is created by SQL server as it has the identity property setup on server.
Like code below:
DataClassAsclepiusImagingDataContext db = new DataClassAsclepiusImagingDataContext();
var matchingSeries = from s in db.Series
where s.DDSeriesInstanceUID == dd.seriesInsUid
select s;
if ((matchingSeries == null) || (matchingSeries.Count() < 1))
{
Series ser = new Series();
db.GetTable<Series>().InsertOnSubmit(ser);
db.SubmitChanges();
}
The problem occures when a few concurent threads trying to execute the same code in a rapid succession, a record may be created by another caller in between the “if record exists?” and “if not create new record”. In such case the first caller would create a duplicate.
What is a good way to ensure that the duplicates are not created in this scenario?
Here are couple of ways to do it.
1) You can add a unique constraint on the database to be absolutely sure that no duplicates can be created.
2) Encapsulate the data insert code within the lock block to ensure that only one thread can execute the insert at a time.