我在我的应用程序的一个类中使用System.Timers.Timer类.我知道Timer类具有继承自实现IDisposable接口的父Component类的Dispose方法.在我的应用程序生命周期中,下面创建的类实例多次; 他们每个人都有一个Timer类的实例,它在类的生命周期中连续生成Elapsed事件.我应该在使用Timer类来配置计时器对象的类中实现IDisposable接口吗?(我见过的代码完全没有这样做).如果我使用下面的类,我担心一些非托管资源将不会被释放:
SomeClass someClass = new SomeClass();
someClass.DoSomething();
someClass = null;
Run Code Online (Sandbox Code Playgroud)
班级:
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;
}
}
} …Run Code Online (Sandbox Code Playgroud) 我写了一个名为QueueManager的类:
class QueueManager
{
Queue functionsQueue;
public bool IsEmpty
{
get
{
if (functionsQueue.Count == 0)
return true;
else
return false;
}
}
public QueueManager()
{
functionsQueue = new Queue();
}
public bool Contains(Action action)
{
if (functionsQueue.Contains(action))
return true;
else
return false;
}
public Action Pop()
{
return functionsQueue.Dequeue() as Action;
}
public void Add(Action function)
{
functionsQueue.Enqueue(function);
}
public void Add(Func<CacheObject,Boolean> function)
{
functionsQueue.Enqueue(function);
}
Run Code Online (Sandbox Code Playgroud)
当我创建这个类的实例并调用Add方法时,它适用于没有参数的函数,例如:functionQueue.Add(Method); ,但是在调用具有参数和返回值的方法时(在我的情况下,ClassType作为参数,并且Boolean作为返回值),例如functionQueue.Add(Method2(classObject)); 它不编译,我错过了什么?
我写了一个应用程序,每10秒通过FTP下载文件,我有以下计时器的代码.
timer3.Tick += new EventHandler(updateLogs);
timer3.Interval = (1000) * (10);
timer3.Enabled = true;
timer3.Start();
Run Code Online (Sandbox Code Playgroud)
我的updateLogs函数:
timer3.Enabled = false;
server1_log = downloadLog("192.168.0.217", 1);
server2_log = downloadLog("192.168.0.216", 2);
server3_log = downloadLog("192.168.0.215", 3);
timer3.Enabled = true;
Run Code Online (Sandbox Code Playgroud)
我意识到请求可能需要超过10秒,这就是为什么我在调用downloadLog()之前禁用定时器,然后启用它.
不过,大约一分钟后,应用程序冻结,CPU使用率跃升至45%以上.当我注释掉timer3的代码时,应用程序运行很长时间并且永远不会崩溃.
有任何想法吗?