Static SortedList and Garbage Collection

C

Chris Bardon

I'm working on a class library in .net, and am having a problem that I
can only describe as a memory leak (which garbage collection was
supposed to eliminate). My class library contains a single class, one
member of which is a static SortedList of session data objects. One
of my methods creates a new object on this list, and another removes
the item from the list, which should make it eligible for garbage
collection. I've tested this in a multithreaded setting though, with
new threads creating a new session, calling Sleep(), and then removing
the session. I can see the memory increase, but nothing ever seems to
decrease. My code looks something like this:

public class SessionData
{
public ArrayList Ports=new ArrayList();
}

public class ClassLib
{
public static SortedList Sessions=new SortedList();
private statid int iNextSessionID=0;

public static int CreateSession()
{
Monitor.Enter(Sessions);
SessionData session=new SessionData();
Sessions.Add(iNextSessionID,session);
iSessionID=iNextSessionID;
iNextSessionID++;
Monitor.Exit(Sessions);
return iNextSessionID;
}
public static void RemoveSession(int iSessionID)
{
Monitor.Enter(Sessions);
SessionData s=(SessionData)Sessions[iSessionID];
s.Ports.Clear();
Sessions.Remove(iSessionID);
Monitor.Exit(Sessions);
}
}

Is there something else that I have to do in my RemoveSession() method
besides removing the object from the SortedList to get it to be
collected by the GC? I've tested the garbage collection by calling
GC.Collect() in my test app.
 
N

Nicholas Paldino [.NET/C# MVP]

Chris,

You should not be using directo calls to Monitor.Enter and Monitor.Exit.
Rather, you should use the lock statement, as it will clean up correctly if
an exception is thrown.

Just because you don't see the memory decrease doesn't mean that your
object was not disposed of. Looking at the memory numbers is not the proper
way to determine if your object was GCed, because that number is a measure
of the working set, which is not related to what you are trying to find out.

Assuming that you are not setting the object to be referred to anywhere
else (and it looks like you are not), I would not assume that the GC is not
working correctly.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top