I currently have a class where I am storing a static collection that gets objects added and removed as certain methods are called. Here is the current code:
public class MatchMaker : Hub
{
private static HashSet<SoloUser> soloUsers = new HashSet<SoloUser>();
//Client Requests
public void findNewPartner(string Name, string Country)
{
SoloUser soloUser = soloUsers.Users.FirstOrDefault(s => (s.Name == Name) && (s.Country == Major));
if (soloUsers.Users.Count > 0){
Clients.partnerRequestResult(soloUsers.Users.FirstOrDefault());
soloUsers.Users.Remove(soloUser);
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
Debug.WriteLine("TotalMemoryUsed: " + totalBytesOfMemoryUsed);
}
else
{
soloUser = new SoloUser {
Name = Name,
Country = Country
};
soloUsers.Users.Add(soloUser);
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
Debug.WriteLine("TotalMemoryUsed: " + totalBytesOfMemoryUsed);
}
}
}
When I run:
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
Debug.WriteLine("TotalMemoryUsed: " + totalBytesOfMemoryUsed);
an object is added or removed from the collection the output of totalBytesOfMemoryUsed gets larger and larger(by 2mb each time) whether or not i add or remove the object from the collection, is this due to a memory leak? Is this even a sufficient way to check memory management? Do i need to dispose an object when i remove it from the collection?
It is a good practice to dispose of any objects that implement
IDisposableas soon as you are finished with them.Given that, you need to remember that the .NET Garbage Collector is non-deterministic. This means you aren’t going to necessarily know beforehand when a collection is going to occur. When the run-time needs to perform a collection, it will try and do that. You shouldn’t be afraid of 2mb anyways. Let the Garbage Collector do it’s job.
Trying to analyze your program’s memory usage by getting the working set of memory or looking at the Windows Task Manager is usually a trip down the rabbit hole. Use a memory profiler after you actually have a problem (such as ANTS).
I also suggest reading MSDN regarding the Garbage Collector in general. You can start here.