public class MyDbContext : DbContext
{
....
static readonly object lockObject = new object();
public override int SaveChanges()
{
lock (lockObject)
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
lock (lockObject)
return base.SaveChangesAsync(cancellationToken);
}
}
I want to use DbContext in multiple threads, but the underlying database has a problem if two threads are writing at the same time. So I am using lockObject to prevent two SaveChanges() at the same time.
That works fine in SaveChanges(), but I don't know how to do the same in SaveChangesAsync(). I think the solution above is wrong. How can I apply the lock to SaveChangesAsync?
Thank you!