Should I dispose of each child control before disposing of the parent control?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • medicinesoup
    New Member
    • May 2010
    • 5

    #1

    Should I dispose of each child control before disposing of the parent control?

    I am using Visual Basic .Net 2005 professional.

    From what I understand, I should be disposing of any object that is an unmanaged resource. I understand the best way to tell if a resource is unmanaged is if it has a Dispose method. ie: If I type a dot after my object, intellisense shows .Dispose() as one of the options. If it does, it's an unmanaged resource. Is that correct?

    In that case, pretty much every control is an unmanaged resource: buttons, forms, panels, etc.

    In the application I am working on I use an MDIparent container form, which contains MDI children forms, which themselves contain Panels, Menus, Groupboxes, etc, which in turn contain Buttons, Textboxes, Labels, Dropdowns, etc.

    Do I have to dispose of each button, textbox, label and dropdown within a panel before disposing of the panel?
    Do I have to dispose of each panel, menu, and groupbox before disposing of the MDI child form?
    ...Or can I just call the Dispose() method of the MDIchild form and the GarbageCollecto r will take care of all the controls and resources within the form?

    Watching the "mem usage" in Windows Task Manager seems to be an unreliable way to detect if I have a memory leak. The numbers just keep climbing and falling (mostly climbing) erratically and without any activity performed on the application. Is there some (relatively) easy way to detect leaks?
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    "I might suggest you jump up 5 years." No you may not.
    Ok. Then use 5 year old technology. I never said I wouldn't answer your question unless you updated. I *suggested* you might want to take advantage of newer capabilities. With so much experience in computing I don't have to insult you by explaining that 5 years of advancements are considerable. But you know your situation far better than I do. For all I know your client base (which may be 10,000 or just your household) is still running WinME or Win2k, not using multiple processors, not using hyper-threading, using one monitor and less than 2 gig of RAM. -or- Maybe you are programming for PC104 based computers running WinXPembeded and only have .NET framework 1.1 at your disposal. I don't know. So you may have a genuine need to stay with 2005. No harm, no foul. It was just a suggestion. Lighten up.

    Not to mention the topic of C# is inappropriate in this subforum titled "bytes > visual basic .net > visual basic .net questions"
    The topic if this thread is whether or not to dispose of your child controls controls before the parent controls - isn't it? In all reality this thread should be under .NET and not VB because whether or not to dispose of an object is language independent. Garbage Collection and object disposal is the same throughout all of the .NET languages. C#, F#, VB... all compile down to the same MSIL. Disposing of objects remains the same.

    If I type a dot after my object, intellisense shows .Dispose() as one of the options. If it does, it's an unmanaged resource. Is that correct?
    No, it's not. In practical (not deep technical) use that's 180 degrees backwards. If it has a .Dispose() method then it managed *but* might make use of unmanaged resources within itself.

    All it really means is that class has a .Dispose method and nothing more. If it is a .NET control such as a Button, then that .Dispose() method is inherited from the base 'Control' object and comes from the IDispose interface. It is the method that is supposed to handle disposing of all the unmanaged resources *within* the class such as event subscriptions and streams.
    http://msdn.microsoft.com/en-us/libr...e.dispose.aspx

    All controls inherit from 'Control' which is managed. That's where you are getting the .Dispose() method from: It is inherited. You don't have to expressly .Dispose() of any of them as they will be disposed of when they go out of scope and the Garbage Collection gets around to it. .Dispose() is run automatically when the object is disposed of by the GC. GC can be forced to happen when you want it to, and not when it feels like it with GC.Collect() but that shouldn't be over used as it will cause a performance hit.

    Now, since .Dispose() is inherited you don't really know how much it does in any given control. It might be 1,000 lines of meaningful code in a "widget" yet be nothing more than a call to the base dispose method in a "gadget".

    .Dispose() is nothing more than a method written into a class. Any class you make can have a .Dispose() method. It's presence or absence does not guarantee the class is managed or not. I often modify the default .Dispose() to handle custom cleanup. For example, when something is being disposed of but has settings that need to be saved, or event handlers detached.

    Which reminds me... If you have a control that you have subscribed event handlers to... then dispose of the control without unsubscribing.. . There's a leak.

    The unmanaged items that can cause memory leaks tend to be things that are nothing more than .NET wrappers around unmanaged WinAPI functions. Often times these can be hidden in DLL's that you are using. Or poorly written drivers for peripherals. There are also some deeply hidden things that can fall into this category, that you wouldn't expect. One example from my own coding, that drove me nuts for a week:
    I had a bitmap resource that said "Photo loading" on a nice gradient blue->black background. I would set the PictureBox to this image while I loaded the image over the network. Then replace it with the loaded photo. It turns out that buried deep in this is some WinAPI function that never released the 12k of RAM used by the resource bitmap. The memory use was almost invisible at only 12k. It wasn't until I set a loop on the function to load thousands of photos did it become clear. So either the PictureBox has a bug, or the way it accesses resources does. Either way I had to make my own.

    My post was not an introductory question.
    Well... yeah... some of it is anyway..
    Do I have to dispose of each button, textbox, label and dropdown within a panel before disposing of the panel?
    The answer to this is: No... and yes. Depending on your situation. All of these things will eventually fall out of scope and be disposed of. Garbage Collection will take place when the operating system feels like it, either do to a need for resources or because it goes idle, or whatever odd rules MS set that they don't share with the rest of us. So if you have a program that just hammers all the time, then you might see benefit to expressly disposing and forcing a GC.Collect each time you finish a large, intensive operation. But as a rule you don't have to. I pretty much only have to do this after fairly advanced graphic manipulation - but that's the area of coding I work in. Your mileage may vary.

    Personally I worry less about calling .Dispose() and just wrap things such as memorystream in 'using' constructs so as to expressly define their scope - letting them clean up after themselves automatically when done.
    http://msdn.microsoft.com/en-us/libr...02(VS.80).aspx
    Don't blast me for pointing you at a C# page. It was the top hit from googling "MSDN using". It also has an example of implementing IDispose and showing that .Dispose() happens when an object goes out of scope without having to expressly call it.

    ...In which case; assuming I am a beginner asking for a handout is just arrogant.
    I never called you a beginner. I suggested some beginner books because I know they cover certain concepts very well and in easy to follow language. I do this for a living and my applications are deployed currently in 7 different countries: And I still find myself referring to 'intro' books quite often because the author touched on something well, completely and concisely. Sometimes you just need to look something up in a page, not an entire chapter.

    I would assume I only need to dispose of the parent, but evidence I have come across tells me that is not adequate and unmanaged resources are still being leaked.
    Memory leaks can happen in more ways than MS would like us all to believe. Often times we learn of them only after we create them and hunt them down, then yell at the air dismayed that MS allowed one of their controls out the door with such a problem. Let me just ask you: What do you have, or what is it you are using that is an unmanaged resource? What is the nature of your application and what 'unmanaged resources' are you using that you think you need to clean up after?

    Is there some (relatively) easy way to detect leaks?
    No. Because memory use is memory use. Keeping 10,000 objects might be what your program does, or it might be a bug. Pick up a copy of MSDN magazine; I see 3-4 memory leak detection programs advertised every month. I think "ANTS" was one that looked good, though I have never used any of them.

    Please don't be insulted when I say that very often what people think are leaks are actually design flaws. Objects/Controls get made but don't actually fall out of scope. Maybe it is put on screen, then later taken off screen, but still exists in an array or other collection. You know you are done with that object, but your program doesn't know your intent, only your express action. If you don't take it out of a List<> or collection then the program thinks you will want it again later.

    If you have a 'thing' that you think is responsible for memory loss then test the theory. Write in a little test function that calls your suspect method 10,000 times and watch the memory use and thread count.

    I found several good articles by people with more in-depth knowledge with a google of the terms "MSDN .Dispose"
    Last edited by Niheel; May 22 '10, 08:22 PM. Reason: i unapproved this, because i didn't know what to take out, i'll let you handle that

    Comment

    • medicinesoup
      New Member
      • May 2010
      • 5

      #3
      Originally posted by tlhintoq
      I never said I wouldn't answer your question unless you updated.
      That is true. I assumed you weren't going to answer because, well, because you didn't answer my question at the time. My retort was misdirected. I have seen a lot of people try to answer a question by suggesting an entirely different and unrelated solution that is never what the Original Poster was looking for, and it irritates me. I thought you were doing the same. I apologize.
      Originally posted by tlhintoq
      I don't have to insult you by explaining that 5 years of advancements are considerable.
      Yet you go on to explain just how considerable those advancements are. How insulting. :) just kidding. I am learning all the new features of .net 2010, but this particular application requires vb 2005. As you said: "So you may have a genuine need to stay with 2005." Bingo.

      Originally posted by tlhintoq
      Originally posted by medicinesoup
      My post was not an introductory question.
      Well... yeah... some of it is anyway..
      Ok. What parts? I'm not trying to start drama, I really do want to know which parts of my post seemed introductory. I can see you felt like I was asking a beginner question, so I would like to make sure I avoid the same mistake in the future.

      Originally posted by tlhintoq
      I never called you a beginner
      I'm sorry, I disagree, and so does your above quote about the post being introductory. "It's not that people here don't want to be helpful, but there is a certain amount of basic learning work that one should really take upon themselves before asking for help." Is a pretty clear statement that says "you are not worth my time since you were clearly just born this morning." I understand that is irrelivant now that we are focusing on the problem, I'm just suggesting you reword that kind of response to avoid giving these forums a reputation of condescension. The links suggested are all resources I've probably used many times in the past, but none of them explained the phenomena I was seeing.

      Originally posted by tlhintoq
      Memory leaks can happen in more ways than MS would like us all to believe. Often times we learn of them only after we create them and hunt them down, then yell at the air dismayed that MS allowed one of their controls out the door with such a problem.
      Agreed. I actually find it strangely comforting that you say that.

      Originally posted by tlhintoq
      what is it you are using that is an unmanaged resource? What is the nature of your application and what 'unmanaged resources' are you using that you think you need to clean up after?
      The problem is that I am assuming I missed one somewhere because I am seeing what looks like a leak. So if there is an unmanaged resource that I didn't clean up, it's because I didn't know it was an unmanaged resource. How can I determine if a resource is managed or not. I figured it would be pretty clear, (API's, brushes, modal forms, shared subscribed events, etc.) but apparently not. I could post all my code, but I'm pretty sure that's not allowed. :)

      Originally posted by tlhintoq
      I see 3-4 memory leak detection programs advertised every month. I think "ANTS" was one that looked good, though I have never used any of them.
      Good pro-tip. Thanks. I will check that out.

      Originally posted by tlhintoq
      Please don't be insulted when I say that very often what people think are leaks are actually design flaws.
      I never said I wasn't to blame for the leak. I'm not insulted by that at all.

      It sounds like you are saying "No, any leaks you have are not caused by failing to dispose of nested controls, but if they are to blame, there isn't much you can do about it. Only the leaks caused by 3rd party code, external API's or the like are within your control to resolve, so concentrate on those." Sounds good to me! Thanks.

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        Please don't take this personally, or that you (or your post) are the reason for this but...

        I am bowing out of my participation on the Bytes site. There are many talented people here and I'm sure someone will be able to answer any future questions you may post.

        Comment

        Working...