Reputation: 1057
I am dealing with some legacy code that probably predates .NET 2. The library itself is custom asynchronous TCP communication layer used by our server.
There is a class there inheriting from System.Net.Sockets.TcpClient
and the whole class hierarchy around it that implements dispose pattern and finalizers (the latter likely not needed).
My question is about suspicious line of code found in the method that handle TCP client disconnected event:
// Hack to ensure that client has disconnected
GC.Collect();
which is executed after calling methods disposing of our communication class hierarchy that eventually calls System.Net.Sockets.TcpClient Dispose
method.
On a 64-bit server that can serve many clients and use gigabytes of RAM these calls can be quite expensive. I could not find anything about forcing garbage collection upon TCP client disconnection?
Upvotes: 1
Views: 854
Reputation: 14894
Two things will happen after you force GC with GC.Collect()
.
The comment suggests that GC.Collect()
is not called to reclaim memory, but rather to execute finalizers to dispose unmanaged resources.
If IDisposable
is used correctly, there is no need to rely on finalizers. Probably there are some IDisposable
objects that are not Dispose
d correctly. You'll have to find them. One way to do it is to examine what finalizers are executed. Some memory profilers can also track such objects (for example .NET memory profiler's Dispose Tracker).
Upvotes: 2