How to avoid garbage collection in real time .NET application?

Seb picture Seb · Sep 17, 2008 · Viewed 25.5k times · Source

I'm writting a financial C# application which receive messages from the network, translate them into different object according to the message type and finaly apply the application business logic on them.

The point is that after the business logic is applied, I'm very sure I will never need this instance again. Rather than to wait for the garbage collector to free them, I'd like to explicitly "delete" them.

Is there a better way to do so in C#, should I use a pool of object to reuse always the same set of instance or is there a better strategy.

The goal being to avoid the garbage collection to use any CPU during a time critical process.

Answer

Joel Coehoorn picture Joel Coehoorn · Sep 17, 2008

Don't delete them right away. Calling the garbage collector for each object is a bad idea. Normally you really don't want to mess with the garbage collector at all, and even time critical processes are just race conditions waiting to happen if they're that sensitive.

But if you know you'll have busy vs light load periods for your app, you might try a more general GC.Collect() when you reach a light period to encourage cleanup before the next busy period.