TsunamiCoder
TsunamiCoder

Reputation: 120

Timer dispose in C#

If my class does not implement IDisposable interface, and if the class has a timer as an object what is the best way of disposing the timer as we can not dispose it in the class destructor, because the call to the class destructor is non deterministic?

Upvotes: 1

Views: 6647

Answers (3)

Kamalesh Wankhede
Kamalesh Wankhede

Reputation: 1505

Any class which has disposable resources should implement IDisposable interface so that those resources can be properly released in Dispose method.

public class MyClass : IDisposable
{
    private Timer _timer = new Timer();

    public void Dispose()
    {
        //This way you can dispose your disposable resources used in class properly.
        _timer.Dispose();
    }
}

Upvotes: 3

Herman Van Der Blom
Herman Van Der Blom

Reputation: 812

The Timer class is missing a IsDisposed property. There is a field variable disposed. With reflection you can then implement the IsDisposed property. This is needed because the Timer object is not set to null when disposed. If you then try to accidently Start the Timer again you get the message that its already disposed. With a check you can prevent this.

Why this could be a problem? When a Timer is implemented in a Windows Service this could be a problem. At some moments the Timer can be stopped and started again. But it should also be possible to Dispose the Timer. If the Timer is at that moment busy in a worker thread this can be a problem.

Upvotes: 0

Henningsson
Henningsson

Reputation: 1325

If your class uses disposable resources, your class should implement IDisposable.

Upvotes: 5

Related Questions