When does context get disposed in various situations

时间:2016-04-04 17:09:31

标签: c# entity-framework

will situation 1 and/or 2 cause it to sit around waiting for GC. I find that the context being used multiple times is causing our code to have methods that have nothing but a using block and I'd like to avoid the using block in those cases if the context will get disposed quickly enough. An example would be a method which does some saving and opens up the context -> saves data to multiple tables -> then returns 200 OK.

Situation 1

public function test()
{
    return new myContext().Events.FirstOrDefault();
}

Situation 2

public function test2()
{
    var ctx = new myContext();

    return ctx.Events.FirstOrDefault();
}

Situation 3

public function test3()
{
    Event e;
    using(var ctx = new myContext()) {
        e = ctx.Events.FirstOrDefault();
    }

    return e;
}

2 个答案:

答案 0 :(得分:0)

any instance is sitting around and waiting for GC. in case of using - we mark it is ready to be collected (solution 3). Solution 1.2 will do the same after exiting the scope.

答案 1 :(得分:-1)

Solution 1 and 2 will not dispose the context. Disposing the context means that unmanaged resources will be cleaned up. Setting your context to null or leaving the scope will not trigger such a clean up. You should either use using construct or add some code where you explicitly call context.Dispose (either in try...finally or any other preferred way (for example, you may decide to make your custom class to implement IDisposable, and dispose the context there)

Entity Framework and context dispose

Uses of "using" in C#

Will the Garbage Collector call IDisposable.Dispose for me?