1

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.

4
  • Then don't use "fetch-and-save". What you describe is an UPDATE. What's the point of loading an object if you only want to update some values? Commented Jul 5, 2017 at 13:42
  • 1
    EF DbContext and related are not thread-safe. I think this should answer your question. Commented Jul 5, 2017 at 13:42
  • First of all, I want to thank you all for the comments. Panagiotis I think you misunderstood my question, it's not an update, I'm dealing with new data all the time, it's more like fetch-and-store. I'll be calling a service to provide me with new data all the time, data that I have to store in a database. @Ivan I got the idea but what if I create a new DbContext in each thread? Would EF will queue the insert commands or will give me some sort of locking exception? Commented Jul 6, 2017 at 1:07
  • You CAN have multiple DbContext instances. Just make sure they don't try to update the same row in the database. Then multiple DbContextinstances can run on different threads. Commented Jul 7, 2024 at 11:21

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
I've added that as a precision

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.