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?
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