Windows Services CPU使用 [英] Windows Services CPU Uses

查看:85
本文介绍了Windows Services CPU使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows服务上工作,每天在特定的时间从数据库中获取一次数据,并且我同时使用使用System.Timers"和使用System.Threading;".

当我使用线程时,整个过程都很安全n理想情况下cpu的使用率为0%n当服务处于运行状态时,它占用了2%或3%的cpu.

但是当我将同一应用程序与using System.Timers一起使用时,CPU使用率会超过50%.

我不明白这种情况发生的方式.

我的代码:-
使用计时器

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

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

推荐答案

您的(true)将一直循环运行直到时间12:00,一种肮脏的方法可能是检查距离触发时间很远,您要睡5分钟左右.尽管这不是推荐的解决方案.

另一种解决方案是编写您的应用程序以仅执行任务,然后使用Windows内置的Task Scheduler将应用程序附加到该应用程序上,并让Windows负责计时/触发.


您读过这篇文章吗?
.NET的新任务计划程序类库 [
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[^]


这篇关于Windows Services CPU使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆