Nikita Kisel Nikita Kisel - 2 months ago 8x
ASP.NET (C#) Question

ASP.NET Web API - Thread safe logic for updating an entity

I have the following method for adding or updating an entity of type

for some User. This method is a part of a Service class a new instance of which is created for each request.

public async Task SaveItem(int userId, string name)
var item = await _context.Items.Where(i => i.UserId == userId).SingleOrDefaultAsync();

if (item == null)
item = new Item
UserId = userId,
Name = name
item.Name = name;
_context.Entry(item).State = System.Data.Entity.EntityState.Modified;

await _context.SaveChangesAsync();

The problem is that two concurrent requests may create two items for the same user which is not valid. For me it looks like a pretty common piece of code and I wonder what is the default way of dealing with this kind of concurrency issue.


You have to handle Concurrency Conflicts properly on your application.

1.Pessimistic Concurrency (Locking)

If your application does need to prevent accidental data loss in concurrency scenarios, one way to do that is to use database locks. This is called pessimistic concurrency. For example, before you read a row from a database, you request a lock for read-only or for update access. If you lock a row for update access, no other users are allowed to lock the row either for read-only or update access, because they would get a copy of data that's in the process of being changed. If you lock a row for read-only access, others can also lock it for read-only access but not for update.

2.Optimistic Concurrency

The alternative to pessimistic concurrency is optimistic concurrency. Optimistic concurrency means allowing concurrency conflicts to happen, and then reacting appropriately if they do.

Please read Handling Concurrency with the Entity Framework article for more info.