Search code examples
c#multithreadingentity-framework-ctp5locks

Method that adds elements to a DbSet from multiple threads


static Object LockEx=new Object();
public void SaveMyData(IEnumerable<MyData> list)
    {
        lock (LockEx)
        {
            using (PersistencyContext db = new PersistencyContext())
            {
                foreach (var el in list)
                {
                    try
                    {
                        db.MyData.Add(el);
                        db.SaveChanges();
                    }
                    catch (DbUpdateException)
                    {
                        db.Entry(el).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
        }

    }

This methods is called from multiple threads. Right now I use a static lock to avoid 2 threads to save data at the same time. Though this is wrong because I only want to save data. The catch is used to create an update query in case the insert (Add) fails because the entry already exists.

What happens if I remove the lock. How will the SaveChanges work? How should my code look like? Thanks


Solution

  • I would remove the lock because the database already handles concurrency anyway by design, then I will also verify if the record exists before trying to add it, then I would do the add or update depending on this result. Just to avoid exceptions because they are performance killers.