Life after using statement

82 views Asked by At

Is the field equals null after using statement?

class Program
{
    MyDBContext context;
    public void Start()
    {
        Run1();
        Run2();
        ...
    }
    void Run1()
    {
        using (context = new MyDBContext())
        {
            //...some context machination
        }
    }
    void Run2()
    {
        if(context != null)
        {
             //?? GC not collect context (memory leak)
        }
    }
}

In my application, i have memory leak. Leak in class which working with entity framework. Maybe context not collecting by GC, mayby he store many secret information somewhere else.

3

There are 3 answers

0
JoelC On BEST ANSWER

The using statement only automatically runs the context.Dispose() method of an IDisposable object. So your object will not be null after the using statement unless you explicitly set it to null.

Also, the creator of MyDBContext will need to handle internal cleanup properly in the Dispose() method or else you could still have memory issues (especially with unmanaged objects).

0
Eren Ersönmez On

using won't make your context null -- it will just call the Dispose() method on it.

You shouldn't define the context as a private field, define it as a local variable instead:

class Program
{
    // MyDBContext context;
    public void Start()
    {
        Run1();
        Run2();
        ...
    }
    void Run1()
    {
        using (var context = new MyDBContext())
        {
            //...some context machination
        }
    }
    void Run2()
    {
        using (var context = new MyDBContext())
        {
             // ...
        }
    }
}
0
dcastro On

At the end of the using block, the MyDBContext.Dispose method will be called, freeing any unmanaged resources (assuming the method has been correctly implemented), but the field will not be set no null.

Not setting it to null should not be the cause of your memory leak. The problem is elsewhere.