如果您在应用程序中使用 System.Timers.Timer 是否有必要处理它? [英] Is it necessary to dispose System.Timers.Timer if you use one in your application?
问题描述
我在应用程序的其中一个类中使用 System.Timers.Timer 类.我知道 Timer 类具有从实现 IDisposable 接口的父 Component 类继承的 Dispose 方法.下面类的实例在我的应用程序生命周期中创建了很多次;他们每个人都有一个 Timer 类的实例,在类的生命周期中连续生成 Elapsed 事件.我应该在使用 Timer 类来处理计时器对象的类中实现 IDisposable 接口吗?(我见过根本不这样做的代码).如果我像这样使用下面的类,我担心一些非托管资源不会被释放:
I am using System.Timers.Timer class in one of the classes in my application. I know that Timer class has Dispose method inherited from the parent Component class that implements IDisposable interface. Instances of the class below are created many times during my application lifecycle; each of them has an instance of Timer class that generates Elapsed events continuously during the class's lifecycle. Should I implement IDisposable interface in the class that uses Timer class to dispose the timer object? (I have seen code that doesn't do this at all). I am afraid that some unmanaged resources will not be freed if I use the class below like this:
SomeClass someClass = new SomeClass();
someClass.DoSomething();
someClass = null;
班级:
using System.Timers;
public class SomeClass
{
private Timer m_timer;
public SomeClass()
{
m_timer = new Timer();
m_timer.Interval = 1000;
m_timer.Elapsed += new ElapsedEventHandler(m_timer_Elapsed);
m_timer.AutoReset = false;
m_timer.Start();
}
public void DoSomething()
{
}
private void m_timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
//Do some task
}
catch (Exception ex)
{
//Ignore
}
finally
{
if (m_timer != null)
{
//Restart the timer
m_timer.Enabled = true;
}
}
}
}
推荐答案
一般来说,您应该始终处理一次性资源.在你上面概述的情况下,我当然会寻找.如果在实现定时器的类上实现 IDisposable,则可以在 using 语句中使用该类,这意味着在释放类时将显式释放资源.
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.
这篇关于如果您在应用程序中使用 System.Timers.Timer 是否有必要处理它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!