Why should you implement IDisposable to clean up unmanaged resources?

documentation says

You should implement IDisposable only if your type uses unmanaged resources directly.

Based on the main Java background, this sounds weird to me. Suppose I have a class containing an IDisposable element:

class Foo : IDisposable {
    private StreamWriter sw;
    ...
}

... and suppose this class is used, for example, as a kind of filter that takes strings and modifies them, and then outputs them using StreamWriter sw. I want to use this class as a kind of Writer.

Why don't I want to implement Dispose(bool)that would trigger sr.Dispose()?This is what I would need to do if I encoded it in Java (the Java interface is Closablesimilar to .NET IDisposable, although somewhat different). However, the documentation says that I should not, because I do not directly use unmanaged resources.

If I do not redefine Dispose(bool)how the managed resource swbecomes deleted when I leave the block launched by the statement using?

+4
source share
2 answers

You must implement IDisposablewhen your class contains a field IDisposable, for example, << 22>.

, ( StreamWriter) , , IDisposable, .

IDisposable(bool), sr.Dispose()?

, , .

Dispose(bool), sw , , using?

. ( IDisposable), , .

+3

, IDisposable, using.
.
, IDisposable. Dispose(bool).

, , . - , System.Timers.Timer, start, stop doWork.
, , IDisposable Dispose(bool).

( , , )

public abstract class Schedualer : IDisposable
{
    private Timer _timer;

    public Schedualer(double interval)
    {
        _timer = new Timer(interval);
        _timer.AutoReset = true;
        _timer.Elapsed += _timer_Elapsed;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_timer != null)
            {
                _timer.Elapsed -= _timer_Elapsed;
                _timer.Dispose();
            }
        }
    }

    protected abstract void OnTimerElapsed();

    protected void StartTimer()
    {
        _timer.Start();
    }

    protected void StopTimer()
    {
        _timer.Stop();
    }

    private void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _timer.Stop();
        TimerElapsed();
        _timer.Start();
    }
}
+1

Source: https://habr.com/ru/post/1693839/


All Articles