I was wondering if the DbContext
class is thread safe, I am assuming it's not, as I am currently executing paralell threads that access the DbContext
in my application and I am getting a host of locking exceptions and other things that look like they may be thread related.
Until recently I wasn't getting any errors...but until recently I wasn't accessing the DbContext
in the threads.
If I am right, what would people suggest as a solution?
I have researched this, and I agree that DbContext is not thread-safe. The pattern I propose does use multiple threads, but a single DbContext is only every accessed by a single thread in a single-threaded fashion.
First, DbContext is a lightweight object; it is designed to be used once per business transaction. Making your DbContext a Singleton and reusing it throughout the application can cause other problems, like concurrency and memory leak issues. And the DbContext class is not thread safe.
EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.
As Daniel mentioned, you don't have to dispose the dbContext. From the article: Even though it does implement IDisposable, it only implements it so you can call Dispose as a safeguard in some special cases. By default DbContext automatically manages the connection for you.
It's not thread safe. Simply create a new instance of DbContext
in you thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With