简体   繁体   中英

Memory leak on entity framework

I created few static list for the records which are being used as look up during application cycle.

However when inspected on the memory profiler and see the object context is being disposed however the GC cannot collect the memory because it keeps in references.

Following is the code snippet (I thought using AsNoTracking would break the relationship between context and entity and would allow context to die in piece.)

            private static List<State> _states;

            public static List<State> States
            {
                get
                {
                    if (_states == null)
                        LoadStates();

                    return _states;
                }
            }

            private static void LoadStates()
            {
                using (LeadContextUoW leadContext = new LeadContextUoW())
                {
                    _states = leadContext.States.AllWithNoTracking.ToList();
                }
            }

Please let me know what is the wrong with this code that is causing memory leak.

You have to explicitly detach the entities. In previous versions of EF, you could call context.Detach - but I believe this is the standard method in EF 6.

private static void LoadStates()
        {
            using (LeadContextUoW leadContext = new LeadContextUoW())
            {
                _states = leadContext.States.AllWithNoTracking.ToList();
                foreach(var state in _states)
                    leadContext.Entry(state).State = System.Data.Entity.EntityState.Detached;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM