Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force garbage collection of object you can't dereference?

We are using EWS Managed API which polls MS Exchange for new mail messages after a given interval. With each invocation of the polling call (PullSubscription.GetEvents()) - Microsofts API is failing to properly dispose the NetworkStream and causes memory to proportionately increase. This was previously discussed here, but never resolved. Using ANTS Profiler we were able to determine which objects were continuously growing in memory and isolate the issue.

Now that the issue has been isolated - is there a way to dispose of a NetworkStream created in an external API that we don't have a reference to? GC.Collect() doesn't seem to dispose it since it still has an active reference. What can we do to cleanup the dangling reference? Is there some wrapper we can use to force cleanup of their buggy SDK?

like image 247
SliverNinja - MSFT Avatar asked Oct 25 '11 14:10

SliverNinja - MSFT


People also ask

Is it possible to force garbage collection and how?

If you want to force garbage collection you can use the System object from the java. lang package and its gc() method or the Runtime. getRuntime().

Can we force garbage collector to run?

You can force garbage collection either to all the three generations or to a specific generation using the GC. Collect() method. The GC. Collect() method is overloaded -- you can call it without any parameters or even by passing the generation number you would like to the garbage collector to collect.


1 Answers

There is no way to force GC to release memory for a referenced object!

First of all I would suggest to contact microsoft itself for help with this bug.

Second, are you talking about "disposal" or just memory release? They are two totally different things. (IDisposable pattern, finalizers).

Third, can u just dereference the object that are referencing these objects?

Fourth, one possible solution can be to decompile with reflector the code that is giving you the issue, understand a way you can arrive to the fields that are keeping the referenced objects, use reflection in your code to access the private fields and put them to null. Is a very dirty hack, but if you have no other way is the only thing i can think of. Do this only if you cannot go in any other ways.

like image 87
Salvatore Previti Avatar answered Sep 28 '22 17:09

Salvatore Previti