简体   繁体   中英

ObjectContext not garbage collected

We are running a very simple function in a console application that loops through databases and lists a table into a variable. Of course originally it did more but we stripped it down to just listing 1 table.

We noticed that on every new creation of ObjectContext the memory grows by about 5MB. We have a using() statement for it and even when doing GC.Collect() the memory doesn't get freed.

When we remove the listing of the table and just create new ClassEntities the memory stays really low.

We tried everything we could to destroy AND collect but to no avail, resulting into a memory use of over 1GB.

Here is the main program:

List < string > databases = (from x in admin_db.tblDbs select x.db_name).ToList();
foreach(var db_name in databases) {
    Console.WriteLine("Current db:" + db_name);
    var entityString = String.Format("metadata=<here we put the connection string>", db_name);
    using(ClassEntities db = new ClassEntities(entityString)) {
        try {
            List < tblDepartment > departments = db.tblDepartments.ToList();
            departments = null;
        } catch {}
    }
}

Then the ClassEntities (stripped down):

public partial class ClassEntities: ObjectContext {
    public ClassEntities(): base("name=ClassEntities", "ClassEntities") {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }
    public ClassEntities(string connectionString): base(connectionString, "ClassEntities") {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }
    public ClassEntities(EntityConnection connection): base(connection, "ClassEntities") {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }
}

Any help or ideas would be hugely appreciated.

There is 2 conditions for an object to be garbage collected:

  • It gone out of scope
  • It is no more referenced elsewhere in the program

As your screencast shows you have circular references that prevent expected garbage collection.

Your list of items is referencing connections, that in return references your items (HorekoEntitiesNoLog)

Try the following:

  • Identify the complete graph of object references that constitute your circular references objects graph.
  • Identify and the entry point(s) of this graph.
  • Clear the reference of any entry point of the graph.
  • Call GC.Collect().

If the memory don't get freed after GC.Collect call, either your are missing entry points references clear or your graph is not complete.

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