Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there situations where using will not dispose of an object?

Are there any situations where using will not dispose of the object it is supposed to dispose of?

For example,

using(dbContext db = new dbContext()){ ... }

is there any way that after the last } db is still around?

What if there is this situation:

object o =  new object();
using(dbContext db = new dbContext()){
 o = db.objects.find(1);
}

Is it possible that o can keep db alive?

like image 451
Travis J Avatar asked Nov 29 '22 09:11

Travis J


1 Answers

I think you're confusing two concepts: disposing and garbage collection.

Disposing an object releases the resources used by this object, but it doesn't mean that the object has been garbage collected. Garbage collection will only happen where this are no more references to your object.

So in your example, db.Dispose will be called at the end of the using block (which will close the connection), but the DbContext will still be referenced by o. Since o is a local variable, the DbContext will be eligible for garbage collection when the method returns.

like image 87
Thomas Levesque Avatar answered Dec 07 '22 23:12

Thomas Levesque