c# - Windows 服务内存使用量增加

标签 c# multithreading memory-leaks timer windows-services

我有一个 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)
    {
    }
}

最佳答案

一些想法

  1. ActiveDirectorySmcpClient(如果您不将其用于电子邮件,请纠正我)的使用意味着您正在处理非托管资源,您是否正在处理这些类正确吗?您可能应该将客户端变量作为静态字段并在程序结束时处理它们。
  2. 我不清楚这些行:

    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();

  3. minor 为什么要使用全名,因为您已经使用 System.Threading 添加了名称?

关于c# - Windows 服务内存使用量增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41576401/

相关文章:

c# - 在 PictureBox 上绘制网格

c# - 如何为 WCF 指定自定义 SoapAction

C# 使用语句缓存

java - Java 中带有 GUI 的多线程

c# - 线程实践。建模应用

c# - 在十进制类型中插入逗号

objective-c - Objective-C : Memory Leak issue in Class Method

javascript - Aurelia 自定义元素不是在 Chrome 中收集的垃圾

javascript - 为什么这是 JavaScript 中的内存泄漏?

java - 如何中断被阻塞的同步方法