I have a windows service doing 3 scheduled jobs. First of them is sending an email to employees their shift times. Second one is getting Active Directory information and saving it to local database. Last one is saving active directory photos to file directory.
Each job is done on a separate thread. Timer ticks every 45 seconds. Everything is running perfectly except the memory usage by the service which is increasing steadily.
Do you have any idea what might be causing this?
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)
{
}
}
Just a few ideas for this
ActiveDirectory and SmcpClient (correct me if you aren't using it for emails) usage means that you're dealing with unmanaged resources, are you disposing those classes correctly? You probably should make client variables as static fields and dispose them at the end of your program.These lines are unclear for me:
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 is unmanaged resource too, so, as it's implementing the IDisposable, you should dispose previous one before assigning the new value for the array entry: thread[i].Dispose();
minor Why do you use full names as you already added using System.Threading?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With