0

I know that DbContext is not thread safe. My question is, Why thread safe DbContext for only Read operations is not possible? Except change tracker what causes DbContext not to be thread safe?

Can you explain why 'ReadOnlyDbContext' is not possible?

  • Because designing things that store state in a thread-safe way is hard, and because its dependency injection in this case is relatively cheap. The real question is why you want this. – CodeCaster Mar 08 '23 at 10:40
  • `Read-only operations` doesn't need to be thread-safe, the concept of thread-safe mainly discusses write action, because, the regarding action change the data not reading data. – A Farmanbar Mar 08 '23 at 10:43
  • The Q is not clear. `ReadOnlyDbContext` relation to thread-safe – A Farmanbar Mar 08 '23 at 10:47
  • @AFarmanbar a DbContext keeps quite some internal state while executing a query and materializing the results, even for SELECT queries. – CodeCaster Mar 08 '23 at 11:23
  • @CodeCaster, ef core internal state as you mentioned, is definitely handled by ef core so there is not any concern for thread safety as it is safe. so read operations are thread-safe by default but write operations are not thread-safe and the developer should take care of that either in the state manager and so on. – A Farmanbar Mar 08 '23 at 12:36
  • @AFarmanbar no, that's simply not true. Two concurrent read operations will definitely corrupt a DbContext and/or make it throw. Something being "internal" (i.e. hidden from the developer) does not make something automagically thread-safe. – CodeCaster Mar 08 '23 at 12:49
  • 1
    Does this answer your question? [Is it ok to inject DbContext as singleton when there is only read operations?](https://stackoverflow.com/questions/64568030/is-it-ok-to-inject-dbcontext-as-singleton-when-there-is-only-read-operations) – CodeCaster Mar 08 '23 at 12:51
  • @CodeCaster, wow, really ... that's a really surprising fact – A Farmanbar Mar 08 '23 at 12:53

0 Answers0