Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is DbContext thread safe?

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?

like image 951
jcvandan Avatar asked May 25 '11 15:05

jcvandan


People also ask

Is a DbContext per thread in parallel foreach safe?

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.

Should DbContext be singleton?

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.

Should you use using with DbContext?

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.

Does DbContext need to be disposed?

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.


1 Answers

It's not thread safe. Simply create a new instance of DbContext in you thread.

like image 97
DanielB Avatar answered Sep 30 '22 20:09

DanielB