Slobodan Savkovic
Slobodan Savkovic

Reputation: 1057

Why would I force garbage collection after TCP client closed?

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

Answers (1)

Jakub Lortz
Jakub Lortz

Reputation: 14894

Two things will happen after you force GC with GC.Collect().

  1. Memory used by unreachable objects that don't have finalizers will be reclaimed.
  2. Objects that implement finalizers will be placed on finalizer queue, and the finalizers will be executed soon.

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 Disposed 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

Related Questions