简体   繁体   中英

Dispose not being called

I have seen a few posts on here on ways to get an object disposed when it goes out of scope, but nothing I have tried seems to work.

I have a loadingscreen class I created, so I declare the object in a form's xxx_load function. I want the object to be disposed automatically when it goes out of scope so the hiding of the loading screen will be taken care of automatically.

Here is my loading class

public class Loader : IDisposable
{
    public Loader()
    {
        Form.Loadscreen();
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        Form.UnloadScreen();
    }
}

Here is how I am using it in my code.

using (Loader loader = new Loader())
{
    //... do some loading processing

    loader.Dispose();
}

even though I can verify that loader.Dispose() is being called, there are still times where the object is not being disposed.

Any suggestions?

First of all, you do not need to call loader.Dispose() explicitly: that's the whole point behind having a using block (it calls Dispose automatically).

Second, what do you mean "the object is not being disposed", since Dispose is being called (and there's no way it would not be called; the using ensures that).

Anyway use just

using (Loader loader = new Loader())
{
    //... do some loading processing    

} // loader.Dispose(); will be called automatically. That's IDisposable() for!

Aside from the answers that say IDisposable and the using statement take care of disposing your object:

If you are watching taskmanager for the memory footprint, Dispose() will not make the amount of allocated memory shrink. It is a common misconception that your application memory footprint shrinks and expands at the exact moment memory is allocated and deallocated. This isn't true. While allocating large chunks of memory may make the footprint increase instantly, deallocation doesn't work that way.

If you are still convinced resources are not being let go, you could try a destructor .

However, when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to free those resources. When the object is eligible for destruction, the garbage collector runs the Finalize method of the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM