Search code examples
vb.neteventsuser-controlsdispose

Where to do clean up in a usercontrol?


I have created a usercontrol in VB.NET.

From within this usercontrol, I am playing a (perhaps longer) sound via a call to the API function mciSendString.

I would like to cancel the playing using another API call to mciSendString when the usercontrol is destroyed (because the hosting form is destroyed).

However, it is not clear to me where this should be done in the usercontrol.

Is the under given code the place where I should do this? If not, then where should it be done?

Protected Overrides Sub Dispose(ByVal disposing As Boolean)

Solution

  • Yes, the Dispose method is where you should perform cleanup. Just be aware that it's possible that the Dispose method of a control will not be called until later than you think, e.g. a form displayed by calling ShowDialog will not be disposed when it is closed but must be disposed explicitly, so a dialogue that gets reused will not dispose its controls in between.