My assignment says: "The class must implement the IDisposable interface, and release the occupied resources in the Dispose method." An example of the class I need is presented on the site . How to implement the IDisposable interface and the Dispose method in this case?

or is it implemented simply:

using (fftwtest TEST = new fftwtest()) { //обработка, вызов методов, свойств, интерфейсов } 

or

 fftwtest TEST = new fftwtest() //обработка, вызов методов, свойств, интерфейсов TEST.Dispose(); 

Based on what is presented on MSDN, I wrote the code:

 public class fftwtest : IDisposable { IntPtr pin, pout; float[] fin, fout; IntPtr fplan1; private bool disposed = false; public void InitFFTW(int n) { pin = fftwf.malloc(n * 8); pout = fftwf.malloc(n * 8); fin = new float[n * 2]; fout = new float[n * 2]; for (int i = 0; i < n * 2; i++) fin[i] = i % 50; //copy managed arrays to unmanaged arrays Marshal.Copy(fin, 0, pin, n * 2); //create a few test transforms fplan1 = fftwf.dft_1d(n, pin, pout, fftw_direction.Forward, fftw_flags.Estimate); } public void TestAll() { TestPlan(fplan1); } public void TestPlan(IntPtr plan) { fftwf.execute(plan); } public void Dispose() { Dispose(true); //освобождение вызвали вручную GC.SuppressFinalize(this); //не хотим, чтобы GC вызвал деструктор } protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { } fftwf.free(pin); fftwf.free(pout); fftwf.destroy_plan(fplan1); // Note disposing has been done. disposed = true; } } ~fftwtest() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } } 

Right or wrong?

  • one
    That's right, only in this case you do not need the if (disposing) block. If other IDisposables will be used in your class, then in this block you must explicitly call Dispose on them. Otherwise, it can be removed, for clarity, so to speak. - Eugene Cheverda
  • 2
    In fact, it is recommended that if the release method has already been invoked, then when it is called again, it should return control. Another thing is that, perhaps, the check could be placed in an explicit Dispose (). When calling through the finalizer, the system will figure it out. But I would recommend to rewrite the check itself to reduce the amount of the client code in the form if (this.disposed) return; - Modus
  • Agree with Modus. - Eugene Cheverda

1 answer 1

In the class represented by reference, all code from the FreeFFTW method must migrate to the Dispose(bool disposing) method Dispose(bool disposing) when implementing an interface. And you can see the implementation technique in the MSDN article about IDisposable . After you implement the interface you can use the examples given by you in the question.