Click here to Skip to main content
15,910,603 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i work on a windows service to fetch data from database once in a day on a particulate time, and i work with both "using System.Timers" and "using System.Threading;".

when i use threads the whole process is going safe n cpu uses is 0% in ideal conditions n when the service is in running condition it takes 2 or 3% of cpu.

but when i use the same app with using System.Timers the cpu uses goes more then 50%.

i cant understand way this happens.

my code:-
using timer

C#
System.Timers.Timer timer = new System.Timers.Timer();
public Service1()
{
      InitializeComponent();
}
protected override void OnStart(string[] args)
{
   timer.Elapsed += new ElapsedEventHandler(DoWork);
   timer.Interval = 30000;
   timer.Enabled = true;
   timer.Start();
   System.Diagnostics.Process.GetCurrentProcess().MinWorkingSet = System.Diagnostics.Process.GetCurrentProcess().MinWorkingSet;
}
 
protected void DoWork(object sender, ElapsedEventArgs e)
            {
                  while (true)
                  {
                        DateTime timeNow = DateTime.Now;
                        if ((timeNow.Hour == 12 && timeNow.Minute == 0))
                        {
                              timer.Enabled = false;
                              timer.Stop();
                              fetchdata.fetchdata();
                        }
                  }
            }
 
protected override void OnStop()
            {
                  timer.Enabled = false;
                  timer.Stop();
            }
Posted
Updated 28-Nov-11 20:22pm
v4
Comments
[no name] 29-Nov-11 2:13am    
EDIT: Added "pre" and "code" tag

1 solution

Your while (true) will be running in a loop constantly until the time is 12:00, one dirty method could be to check how far you are away from the trigger time and go to sleep for 5 minutes or something. Although it would not be a recommended solution.

One other solution would be to write your app to perform the task and only the task, and then use the Windows inbuilt Task Scheduler to attach the application to and let windows take care of the timing/trigger.


Have you read this article;
A New Task Scheduler Class Library for .NET[^]
 
Share this answer
 
v3
Comments
RaisKazi 29-Nov-11 5:07am    
My 5.

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