Member 12670645 Ответов: 1

Реализует интерфейс IDisposable


I have built an application in VS2019.  I am implementing the IDisposable interface.  It compiles and runs fine.  But when I run the Code Analyzer I get a warning:

"Warning	CA2213	'MainForm' contains field 'MainForm.myClassInstance' that is of IDisposable type: 'MyClass'. Change the Dispose method on 'MainForm' to call Dispose or Close on this field."

My code looks something like this:

public class MyClass : IDisposable
{
        public MyClass()
        {
            ... Do Some Work Here
        }

        
        ~MyClass()
        {
            Dispose(false);
        }

}

public partial class MainForm : Form
{
        MyClass myClassInstance = null;
        

        public MainForm()
        {
            InitializeComponent();
            UserInitialization();
        }
        private void UserInitialization()
        {
            myClassInstance = new myClass();
            
            myClassInstance.Dispose();

            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
 
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            myClassInstance.Dispose();   
        }
}


Что я уже пробовал:

I have set my object to null, I have called Dispose in my MainForm, I have called the Dispose method in my MainForm_FormClosingEventHandler and I have an explicit destructor in MyClass that calls the Dispose method.... I have also tried "GC.SuppressFinalize(this)" but I still get the warning. I have run the app for days and I don't see any problem but I want to make sure I don't have any memory leaks.  Any ideas appreciated.

1 Ответов

Рейтинг:
0

Ashutosh Gpt

несколько решений, но нет никакой причины, по которой появляется это предупреждающее сообщение.
в настоящее время форма не позволяет переопределить Dispose() из компонента, movingmyClassInstance.dispose в Form.Dispose решил бы эту проблему, но на данный момент Вы можете переместить это свойство в local для вашего метода и подавить его.


#pragma warning disable IDE0069 // Disposable fields should be disposed
        private MyClass myClassInstance = null;
#pragma warning restore IDE0069 // Disposable fields should be disposed