I have a question guys, what would happen if I (using Entity Framework) call SaveChangesAsync() multiple times simultaneously? What would happen when more than one thread is trying to actually write data in the database at the same time? How is it handled? I'm working a project where I have to fetch-and-save periodically and I'm afraid that the time it takes to process each package of data in some cases might be bigger than the time-interval between calls. I'm new to Entity Framework and I find it fascinating, but I still have my doubts regarding the action behind the scenes. Any help will be much appreciated.
1 Answer
If "simultaneously" means by multiple threads then you can't do that because EF is not thread safe.
Here are some examples that might help you.
https://github.com/mjrousos/MultiThreadedEFCoreSample
Reference here:
https://learn.microsoft.com/fr-fr/ef/core/miscellaneous/async
2 Comments
Gert Arnold
It's not said that one context is used in multiple threads, only that multiple
SaveChangesAsync() calls are executed "simultaneously". The question is far too broad and vague to answer.Gabriel
I've added that as a precision
DbContextand related are not thread-safe. I think this should answer your question.DbContextinstances. Just make sure they don't try to update the same row in the database. Then multipleDbContextinstances can run on different threads.