我有一个 Windows 服务执行 3 个预定作业。他们首先向员工发送电子邮件,告知他们的轮类时间。第二个是获取 Active Directory 信息并将其保存到本地数据库。最后一个是将事件目录照片保存到文件目录。
每个作业都在一个单独的线程上完成。计时器每 45 秒计时一次。除了服务的内存使用量稳步增加外,一切都运行良好。
您知道是什么原因造成的吗?
Thread[] thread;
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.AutoReset = true;
timer.Enabled = true;
timer.Interval = 1000 * 45;
timer.Start();
timer.Elapsed += Timer_Elapsed;
servisList = new List<IService>() { new ShiftNotification(), new ActiveDirectoryService(), new DirectoryPhotos() };
thread = new Thread[servisList.Count];
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
for (int i = 0; i < servisList.Count; i++)
{
if (thread[i] == null)
{
if (TimeControl.CheckTime(DateTime.Now, servisList.ElementAt(i).sProps))
{
thread[i] = new System.Threading.Thread(new System.Threading.ThreadStart(servisList.ElementAt(i).NotifyUsers));
thread[i].Start();
}
}
else
{
if (thread[i].ThreadState != System.Threading.ThreadState.Running)
{
if (TimeControl.CheckTime(DateTime.Now, servisList.ElementAt(i).sProps))
{
thread[i] = new System.Threading.Thread(new System.Threading.ThreadStart(servisList.ElementAt(i).NotifyUsers));
thread[i].Start();
}
}
}
}
}
catch (Exception ex)
{
}
}
最佳答案
一些想法
ActiveDirectory
和SmcpClient
(如果您不将其用于电子邮件,请纠正我)的使用意味着您正在处理非托管资源,您是否正在处理这些类正确吗?您可能应该将客户端变量作为静态字段并在程序结束时处理它们。我不清楚这些行:
if (thread[i].ThreadState != System.Threading.ThreadState.Running) { if (TimeControl.CheckTime(DateTime.Now, servisList.ElementAt(i).sProps)) { thread[i] = new System.Threading.Thread(new System.Threading.ThreadStart(servisList.ElementAt(i).NotifyUsers)); thread[i].Start(); } }
Thread
也是非托管资源,因此,当它实现IDisposable
时,您应该在为数组条目分配新值之前处理掉之前的一个:thread [i].Dispose();
minor 为什么要使用全名,因为您已经
使用 System.Threading
添加了名称?
关于c# - Windows 服务内存使用量增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41576401/