Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Not Garbage Collected

I have a third party component I'm using and I'm seeing some issues with resources not being released. The component causes windows to create a handle to a UDP socket ("\Device\Udp" as well as "\Device\Afd"). If I allow the program to execute and dereference the third party object, I assumed that like all .NET objects I've worked with in the past, the object will get garbage collected. However, Process Explorer is showing that the "\Device\Udp" handles are being kept indefinitely until the actual process is killed (or in the case of the app in question: app pool is recycled.

Furthermore, if I manually call the Dispose() method of the object, then the handles are released. This is the fix I have in place, but I'm just curious about why it is needed. Is it possible that the builders of the componenet have done something or set some attribute which prevents the garbage collector from calling the destructing on the object?

If it helps, I have posted the code below. The code was used in a Forms application, so the process does not end after the while loop completes.

Code that does not work (100 handles created indefinitely):

        for (int i = 0; i < n; i++)
        {
            Snmpmgr mgr = new Snmpmgr();
            mgr.Timeout = 10;

            mgr.ObjCount = 1;
            mgr.ObjId[1] = ".1.3.6.1.2.1.1.1.0";

            try
            {
                mgr.SendGetRequest();  // Handle shows up in ProcExplorer after this call
            }
            catch (Exception ex)
            {
                throw new TimeoutException("Error contacting CMTS.");
            }
        }  // end of for...  obj referenced by mgr never garbage collected

Code that does work (handles created and released):

        for (int i = 0; i < n; i++)
        {
            Snmpmgr mgr = new Snmpmgr();
            mgr.Timeout = 10;

            mgr.ObjCount = 1;
            mgr.ObjId[1] = ".1.3.6.1.2.1.1.1.0";

            try
            {
                mgr.SendGetRequest();  // Handle shows up in ProcExplorer after this 
            }
            catch (Exception ex)
            {
                throw new TimeoutException("Error contacting CMTS.");
            }
            mgr.Dispose();  // UDP Socket Handle freed...  not sure that's how to spell free + ed :)
        }

Thanks in advance for your help.

Chris

like image 958
regex Avatar asked Nov 23 '25 21:11

regex


1 Answers

You used a mgr.Dispose call in the second example. I'll take it mgr is an IDisposable?

In that case, you need to use a using block:

for (int i = 0; i < n; i++)
{
    using(Snmpmgr mgr = new Snmpmgr())
    {
        // Your Code
    }
}
like image 83
MiffTheFox Avatar answered Nov 25 '25 11:11

MiffTheFox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!