[C#]帮助我了解Windows服务 [英] [C#] Help me about windows services

查看:90
本文介绍了[C#]帮助我了解Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建Windows服务时,我将代码添加到OnStart()和OnStop(),但是它们仅在启动和停止服务中起作用.所以,我可以在运行时将什么命令放到命令上呢?
感谢Advance ...

When I create a windows service, I add the codes to OnStart() and OnStop(), but they just work at Start and Stop service. So, what function can I put my commands to they work at RUNTIME...
Thank advance...

推荐答案

最简单的实现方法是在服务中使用计时器控件;这样您就可以每次在计时器刻度上进行一些工作.


在顶部声明以下成员物品.

The simplest way to implement this is to use a timer control in you service; so that you can do some work on the timer tick for each time.


Declare following member vaiables at top.

private System.Timers.Timer ProcessTimer;
        private TimeSpan PollInterval = TimeSpan.FromMinutes(1);
        private DateTime PollTimerStopTime = DateTime.MaxValue;




在服务的OnStart 事件上,初始化您的计时器,如下所示.






On the OnStart event of the service initialize you timer like following.



protected override void OnStart(string[] args)
        {

this.ProcessTimer = new System.Timers.Timer();
                this.ProcessTimer.Interval = this.PollInterval.TotalMilliseconds;
                this.ProcessTimer.AutoReset = false;
                this.ProcessTimer.Elapsed += new System.Timers.ElapsedEventHandler(ProcessTimer_Elapsed);

//Start the timer

this.PollTimerStopTime = DateTime.MaxValue;
            this.ProcessTimer.Start();



}


处理ProcessTimer_Elapsed


Handle the ProcessTimer_Elapsed

private void ProcessTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (e.SignalTime < this.PollTimerStopTime)
            {
             //DoMyWork();
            }
}



您可以在Google上找到有关此示例.



You can find samples on this on google.


通常,在服务中,所有工作都在工作线程中完成. OnStart方法只是启动线程并返回;如果OnStart没有及时返回,则该服务将无法正常启动.在OnStop方法中,所有需要做的就是发信号通知线程退出.然后,工作线程可以自由地运行命令处理器或数据使用者或您需要的任何程序,直到被告知停止为止.
Typically in a service all of the work is done in a worker thread. The OnStart method simply starts the thread and returns; if OnStart doesn''t return in a timely fashion the service won''t start properly. In the OnStop method all that needs to be done is to signal the thread to exit. The worker thread is then free to run a command processor or data consumer or whatever you need until it''s told to stop.


谢谢...
但这不起作用...

有时它可以工作,但是我希望它可以在服务活动中重复一些命令,例如在Windows应用程序中循环

Thank...
But It don''t work...

Sometime it work but I expect it work repeated some commands within service active, like loop while in windows application

while (GetMessage(....))
{
// MyWork

}


这篇关于[C#]帮助我了解Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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