Search code examples
c#.netentity-frameworkusing-statement

Life after using statement


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.


Solution

  • 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).