如何在Windows服务的循环,而无需使用定时器 [英] How to have a loop in a Windows service without using the Timer

查看:839
本文介绍了如何在Windows服务的循环,而无需使用定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要调用从Windows服务业务层的方法,每10秒后(使用C#和.NET完成)。不过,我不希望使用Timer_Elapsed事件,因为它启动另一个线程/进程如果第一个线程/进程仍在运行。我只是需要一个单线程的方法,因为相同的业务方法的多次调用产生不必要的并发症。

I want to call a Business layer method from a Windows service (done using C# and .NET) after every 10 seconds. However, i dont want to use the Timer_Elapsed event since it starts up another thread/process if the first thread/process is still running. I just need a single threaded approach, since multiple calls to the same Business method creates unwanted complications.

所以我加了一个do - while循环中on_start。我知道,因为它产生这个过程中,如果该服务被关闭变成孤儿,这是不正确的方法。

So i added a do--while loop in the on_start. I know this is not the correct way since it spawns this process which becomes an orphan if the service is shut down.

我怎样才能解决这个问题呢?

How can i approach this problem ?

问候,

推荐答案

有另一种方式来获得定时执行时,WaitHandle.WaitOne()方法提供超时参数。这一工程非常漂亮的一个服务,因为它可以让你实现需要停止服务的的定期执行的一个方法调用。模板看起来是这样的:

There's another way to get timed execution, the WaitHandle.WaitOne() method provides a timeout argument. That works very nicely in a service as it lets you implement the need to stop the service and periodic execution in a single method call. The template looks like this:

    Thread Worker;
    AutoResetEvent StopRequest = new AutoResetEvent(false);

    protected override void OnStart(string[] args) {
        // Start the worker thread
        Worker = new Thread(DoWork);
        Worker.Start();
    }
    protected override void OnStop() {
        // Signal worker to stop and wait until it does
        StopRequest.Set();
        Worker.Join();
    }
    private void DoWork(object arg) {
        // Worker thread loop
        for (;;) {
            // Run this code once every 10 seconds or stop right away if the service 
            // is stopped
            if (StopRequest.WaitOne(10000)) return;
            // Do work...
            //...
        }
    }

这篇关于如何在Windows服务的循环,而无需使用定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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