0

I was looking around but couldn't find anything specific for this one. So, I have an async repository, which used to look like:

public object get()
{
   var db = new entity(); //i am using EF6
   var listOfObjects = db.Object.ToList();
   db.Dispose();
   return listOfObjects;
}

but now that I'm using async I can't have the dispose there because it hits it before the previous call is being resolved. So my previous method now looks like:

public async Task<Object> GetAsync()
{
   var db = new entity();
   return await db.Object.ToListAsync();
}

So my question is, when or how should I dispose now?

freshbm
  • 5,525
  • 3
  • 43
  • 70
Spluf
  • 740
  • 10
  • 24
  • Why not just use a using statement? Ef is clever enough to not get rid of the context immediately anyway. The context sits in the application pool and will be reused if other calls are added before its eventually disposed – Matthew Flynn Oct 09 '15 at 06:15
  • i'm not worried that it's gonna dispose of it too fast, on the contrary, this is going to be a big enough project and i don't want all those connections to stack up in memory, i want to dispose of those connections as soon as they are resolved.. I hope this makes sense :) – Spluf Oct 09 '15 at 06:51
  • sorry for not coming back. http://stackoverflow.com/questions/3653009/entity-framework-and-connection-pooling does this help. The edit basically explains briefly how eg handles the context. It's doesn't directly dispose of it immediately. Personally I would let the app pool handle disposing of any contexts. – Matthew Flynn Oct 10 '15 at 11:21
  • yup, this is good, just rewrite it as an answer so i can mark it. Thank you :) – Spluf Oct 12 '15 at 08:35

1 Answers1

1

As we talked about in our discussion and more detail can be foudn on this on the stack link below;

Entity Framework and Connection Pooling

Christopher Harrison also talks about this briefly in the Entity Framework MVA videos at the microsoft virtual academy.

Basically, Entity Framework will create a single entity per context. To quote the link,

Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.

Community
  • 1
  • 1
Matthew Flynn
  • 3,167
  • 2
  • 30
  • 74