Click here to Skip to main content
15,906,329 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have created windows service while running this service CPU utilization high..
Please find the below code..
here ComputeData() method call procedure and this procedure take 1:23 minute to execute time. have set here 5 min interval to execute the ComputeData() method.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Configuration;

namespace UpdateData
{
   public partial class Service1 : ServiceBase
   {
      static Timer timer;
      public Service1()
      {
         InitializeComponent();
      }
      private static void start_timer()
      {
         timer.Start();
      }
      protected override void OnStart(string[] args)
      {
         timer = new Timer();          
         timer.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds;            
         timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
         timer.Enabled = true;
         timer.Start();
      }

      public static bool ExecuteTime()
      {
         TimeSpan StartingTime = new TimeSpan(
            Int32.Parse(ConfigurationManager.AppSettings["StartingTimeHour"]),
            Int32.Parse(ConfigurationManager.AppSettings["StartingTimeMinute"]), 0);
         TimeSpan EndingTime = new TimeSpan(
            Int32.Parse(ConfigurationManager.AppSettings["EndingTimeHour"]),
            Int32.Parse(ConfigurationManager.AppSettings["EndingTimeMinute"]), 0);

         TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
         return ((CurrentTime > StartingTime) && (CurrentTime < EndingTime));
      }

      static void timer_Elapsed(object sender, ElapsedEventArgs e)
      {
         try
         {
            DateTime TodayDate = DateTime.Now;
            if (TodayDate.DayOfWeek == DayOfWeek.Saturday || TodayDate.DayOfWeek == DayOfWeek.Sunday)
            { }
            else
            {
               while (ExecuteTime())
               {
                  BasicBO.ComputeData();
               }
            }
         }
         catch (Exception ex)
         {
            string msg = ex.Message + " at " + DateTime.Now + " From timer_Elapsed method";
            BasicBO.writeLog(msg, "UpdateVMErrorLog.txt");
         }
      }

      protected override void OnStop()
      {
         string msg = "Service Stoped at : " + DateTime.Now;
         BasicBO.writeLog(msg, "UpdateVMStopLog.txt");
      }
   }
}


What I have tried:

so far i have tried to increase time interval 3 to 5 min but problem reaming same.
Posted
Updated 18-Nov-16 0:37am
v2
Comments
F-ES Sitecore 17-Nov-16 5:37am    
You're better setting the timer to fire every second maybe, then in that event check the once if the code should run, ie change the "while" to an "if". As it is your code fires little but when it does fire it runs for a long time. You're better making it fire more often and run for less time.

The issue you'll have with this method is that you'll need some way of remembering that ComputeData has been run for that time interval as the timer will probably fire multiple times within the window you want the code to run in.
Philippe Mori 18-Nov-16 10:19am    
You should probably also set the thread priority lower than normal so that the service won't have too much impact on UI...

The lines that will be chewing up your CPU are
C#
while (ExecuteTime())
{
BasicBO.ComputeData();
}


That is a very tight loop, with no breathing space for the CPU in there. Pop a Sleep in that loop, and I think your problem will go away.

Either that, or perhaps you meant if rather than while there.
 
Share this answer
 
v2
Comments
johannesnestler 17-Nov-16 5:56am    
exactly what I spotted
manish_rcc 18-Nov-16 4:49am    
Thanks for your replay.

look like below code is working for me.

while (ExecuteTime())
{
BasicBO.ComputeData();
Thread.Sleep(5 * 60 * 1000);//sleep thread at every 5 min
}
johannesnestler 18-Nov-16 6:32am    
oh no man - please see my solution...
Hi manish_rcc

please have a look at the modified Code and the comments:

C#
public partial class Service1 : ServiceBase
   {
// 1. Timer not static - one instance per Service...
      Timer timer;

// Configuration can be cached
      TimeSpan startingTime;
      TimeSpan endingTime;

      public Service1()
      {
         InitializeComponent();
      }
      private static void start_timer()
      {
         timer.Start();
      }
      protected override void OnStart(string[] args)
      {
         timer = new Timer();          
// hardcoded interval?
         timer.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds;            
         timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
// no need to call Enable and Start - just Start
         timer.Enabled = true;
         timer.Start();

// Read Configuration only once to cache
         startingTime = new TimeSpan(
            Int32.Parse(ConfigurationManager.AppSettings["StartingTimeHour"]),
            Int32.Parse(ConfigurationManager.AppSettings["StartingTimeMinute"]), 0);
         endingTime = new TimeSpan(
            Int32.Parse(ConfigurationManager.AppSettings["EndingTimeHour"]),
            Int32.Parse(ConfigurationManager.AppSettings["EndingTimeMinute"]), 0);

      }
 
// Better naming: Functions returning booleans should be named with Is/Has/Can...
      public static bool ShouldExecute()
      { 
         TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
         return ((CurrentTime > startingTime) && (CurrentTime < endingTime));
      }
 
      static void timer_Elapsed(object sender, ElapsedEventArgs e)
      {
         try
         {
            DateTime TodayDate = DateTime.Now;
            if (TodayDate.DayOfWeek == DayOfWeek.Saturday || TodayDate.DayOfWeek == DayOfWeek.Sunday)
            {
// Exit early, no need to do the check on weekends (hardcoded values a good idea?)
                return;
            }
            else
            {
// no while here, you are already in a timer(-loop) - just check if operation should run now, timer will come here after 5 minutes (the intervall you specified to the timer, again hardcoded value a good idea?)
               if(ShouldExecute())
               {
                  BasicBO.ComputeData();
               }
            }
         }
         catch (Exception ex)
         {
            string msg = ex.Message + " at " + DateTime.Now + " From timer_Elapsed method";
            BasicBO.writeLog(msg, "UpdateVMErrorLog.txt");
         }
      }
 
      protected override void OnStop()
      {
         string msg = "Service Stoped at : " + DateTime.Now;
         BasicBO.writeLog(msg, "UpdateVMStopLog.txt");
      }
   }


You see - the part you good confused about is, that a timer already represents a Kind of "Loop" to check...

Kind regards
Johannes
 
Share this answer
 
v2
Comments
Midi_Mick 18-Nov-16 7:29am    
I was going to go there for him too - just as soon as my head was straight enough. Well done mate. +5
manish_rcc 21-Nov-16 6:30am    
Many Thanks for help.
johannesnestler 21-Nov-16 8:47am    
you are welcome - everthing clear now and working? (I changed your code out of my head in Notepad...), Feel free to ask futher questions...
manish_rcc 22-Nov-16 5:21am    
Yes Many Thanks ..Code is now working perfectly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900