Is it necessary to dispose System.Timers.Timer if you use one in your application?

与世无争的帅哥 提交于 2019-11-27 13:03:31

Generally speaking you should always dispose of disposable resources. I certainly would be looking to in the case you outline above. If you implement IDisposable on the class that implements the timer you can then use the class in a using statement, meaning resources will be explicitly released when your class is disposed.

I see that you asked this question a year ago but let me throw in my 2 cents worth. Slightly less because of inflation :). Recently I discovered in our application that we weren't disposing of timers. We had a collection of objects and each object had a timer. When we removed the item from the collection we thought it should have been garbage collected. For some reason not so with timers. We had to call dispose on the object in the collection to get rid of the timer before the objects were actually garbage collected.

The rule of thumb I use is to make anything that has an IDisposable object, IDisposable itself (and disposing the child objects only when Dispose is explicitly called)

There's a good discussion on IDisposable at Joe Duffy's blog along with code samples which look very similar to those in my copy of the excellent Framework Design Guidelines book

The timer has to be disposed, or it will keep fireing for some time after you have "finished" with it. However due to thread issues, it may still fire a short time after you have disposed it!

I would guess that the timer object creates or uses a worker thread for the purposes of firing the timer events. The dispose call will free the thread and the resources associated with it. If that is the case, it would be a good idea to call dispose so you don't have unused threads hanging around too long.

By implementing idisposable you will be able to tidy up any internal resources that also implement idisposable such as your timer.

In addition you would be able to change your calling code to use the using statment.

using (SomeClass someClass = new SomeClass())
{  
someClass.DoSomething();  
}  

I agree with Rowland.

There is a rule in FxCop that finds classes containing Disposable objects, but not properly implementing IDisposable.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!