I think the main point of my question is: what is best practise or is Visual Studio 2019 giving me wrong hints about disposing items? This post talks about bugs in the code analysis, but disposing items is still a bit outside my field of good knowledge.
I have a form where I declare some fields:
public partial class FormRequestLines : Form
{
Process view3dProcess;
Process view2dProcess;
Label label;
......
The fields are used to (re)start and kill processes and write and hide to a newly created label in different methods.
To dispose these fields, I created a FormClosed method:
private void FormRequestLines_FormClosed(object sender, FormClosedEventArgs e)
{
if (view2dProcess != null) { view2dProcess.Dispose(); }
if (view3dProcess != null) { view3dProcess.Dispose(); }
if (label != null) { label.Dispose(); }
}
1) Is it correct that the fields should be disposed?
2) Is this the correct way and place of disposing fields?
Visual studio gives me these warnings:
Ps: I use the designer of VS to create a form.
Static code analysis tools expects that you do dispose in Dispose()
method. You need to override the Dispose
method from Form and remove FormRequestLines_FormClosed
.
See difference between Form.Close and Form.Dispose
Typically this is automatically overridden in the FormRequestLines.Designer.cs file, so you will need to move the dispose into your code file so that you can add whatever code you need to add without it being rewritten by the designer.
protected override void Dispose(bool disposing)
{
if (disposing)
{
components?.Dispose();
view2dProcess?.Dispose();
view3dProcess?.Dispose();
label?.Dispose();
}
base.Dispose(disposing);
}