Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will opening a DbContext per ToListAsync end up blocking a connection pool?

Related : EntityFramework (6) and async ( waitingForActivation)?

However, it does not address awaiting multiple items, just one. My goal was to accomplish something along these lines

var car = db.Cars.ToListAsync(); 
var people = db.People.ToListAsync(); 
Task.WhenAll(car,people);

Unfortunately I got this runtime exception (I should have known really)

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

Database contexts aren't thread safe. Okay. So now I am considering factoring out the calls to be methods and then awaiting both method calls (or an easy way to demo this would be to just wrap each of the db calls shown above in using(db){} statements). Regardless, the problem is that with that pattern it will require a new DbContext for each ToListAsync.

Will using a DbContext per ToListAsync call be a threat to a connection pool? Is this an anti pattern?

like image 628
Travis J Avatar asked Oct 31 '13 16:10

Travis J


1 Answers

Will using a DbContext per ToListAsync call be a threat to a connection pool?

It will use one connection per DbContext. Depending on your scenario, this may oversubscribe, or it may not. It depends a lot on the expected usage and the capabilities of your database.

Is this an anti pattern?

Not necessarily. This puts more strain on the DB, as it's going to perform both queries simultaneously. The upside is you're potentially increasing the throughput on the client side (in this case, ASP.NET being the client to the DB), which may outweigh the extra strain. Measuring is really the only way to know whether the benefits outweigh the strain on the DB.

like image 140
Reed Copsey Avatar answered Sep 27 '22 16:09

Reed Copsey