How to know if it is memory leak or not if Mem Usage in Task Manager keep increasing
I wrote a small Server class which basically is a TcpListener wrapper and ThreadPool thread spawner.
The threads run Server::ProcessMessage() which does some work sending messages to and fro and then quits at the end of it.
But just before exiting the function, I also call TcpClient.GetStream().Close() and then TcpClient.Close(). I don't use any Mutex or ManualResetEvent WaitHandles.
Tested the Client and Server, everything works except in task manager it shows the Mem Usage keep on increasing on every Server::ProcessMessage(). Even after all Client apps have been disconnected and closed, the Mem Usage is still there, not decreased.
Server is running as a windows service.
How do I know if it is a sign of memory leak or just garbage collector not doing its job (yet)?
Thanks.
EDIT: I think I found the cause of my "memory leak". I had 开发者_JAVA百科Console.WriteLine() in my Server::ProcessMessage(). Still it would be helpful if there was an easier way to check for memory problems.
Try using WinDbg with SoS extension to check if unneeded objects are still referenced in the heap. Check this link also.
You usually start by using !DumpHeap -type (some-type-or-just-namespace)
to get a list of objects of a certain type (I usually just write the relevant layer's namespace to get a list or objects which I believe might be still in memory).
If you have more than one instance of a certain object, you will need to pick one address which corresponds to the MT for your object, and then call !gcroot (your-address)
to see what's keeping your object alive.
In most cases, objects are kept alive because one of their methods is registered as an event handler for some other object's event. A good practice is to always detach your event handlers from parent classes once your object is no longer needed.
Since it is a webserver, I'd creating a dummy page handler that forces the GC. If the memory will not be freed, the leak suspect could be serious.
Afterward, the real problem is where the leak is!
精彩评论