Winforms: is it safe to delete code in the automatically created Dispose () method created by Visual Studio for Windows Forms

Background

In Visual Studio 2008 Create a new Windows Forms application, this will create a skeleton project with the class "Form1". VS2008 automatically creates the Dispose () method.

/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } 

I wandered into the office of a colleague (senior developer) - a great guy, smart, good design for chat - but I noticed that he was typing - when he switched to the code base, he deleted this section of the Dispose () methods that VS2008 was created for forms.

  if (disposing && (components != null)) { components.Dispose(); } 

So, I asked him why, and he said that he did not need to be stored.

Questions

  • Is it safe to delete this code?
  • What are the advantages / disadvantages of leaving or removing it?
+4
source share
2 answers

Do not delete it at all if there is even the slightest chance that you will ever use something like System.Windows.Forms.Timer in a form. And there is always a chance for this.

This is the code that the timer will have when the form closes, and if you did not select a timer, it will continue to work. I took a few bits of code in which this type of error was introduced (before .NET 2.0 this mechanism didn’t work so well) and the resulting intermittent problems with punching caused by timers that work long after the forms that they need to upgrade, shutting down can be a real pain.

There is no real benefit to removing this - if no controls have added themselves to the list of components, then the components. Dispose () will be trivial to run. If the controls have added themselves to the list, this is because they must be deleted.

+5
source

No, it is not safe to delete this code. Some components depend on how this template acts in order to properly release the unmanaged resources they hold onto. If you delete this code, your application will probably work 95% of the time. 5% of cases will appear as resource leaks, potential memory leaks, inappropriate errors, in general, it is difficult to identify problems.

The best approach to working with a one-time resource is to get rid of the moment when you no longer use it. By following this practice, you will save a lot of headaches in the future. Removing this code takes the exact opposite approach.

This SO post contains a more detailed explanation: When do I need to host objects in .NET?

+7
source

All Articles