Run timer in windows service

时间:2015-11-12 11:23:46

标签: c# timer windows-services

I have a windows service which is checking in a given path if there are new files created. To do that, I made with a timer which is checking every second the creation of new files in the directory. All the actions of the windows service I'm saving in a log through Log4net library. The problem comes when I start the service. It stops when I want to start the timer.

Thats my window service class:

public partial class WindowsService : ServiceBase
{

    private aTimer timer;
    private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public WindowsService()
    {            
        InitializeComponent();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    private void StartTimer()
    {
        timer.StartTimer();
    }

    private void StopTimer()
    {
        timer.CloseTimer();
    }


    protected override void OnStart(string[] args)
    {
        logger.Debug("Service is started.");
        logger.Debug("-----------------------------------------------------------");
        this.StartTimer();


    }

    protected override void OnStop()
    {
        this.StopTimer();         
        logger.Debug("-----------------------------------------------------------");
        logger.Debug("Service is stopped.");

    }
}

Thats it's my Timer class:

public class aTimer
{
    private System.Timers.Timer timer;
    private bool timerTaskSuccess;

    private static readonly String path = "C:\\path\\";
    private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public aTimer() { }

    public void StartTimer()
    {
        try
        {
            timer = new System.Timers.Timer(1000);

            timer.Elapsed += OnTimedEvent;
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();

            timerTaskSuccess = false;
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Error ocurred while starting the timer: '{0}'", ex);
        }

        Watcher watcher = new Watcher();
        watcher.CreateWatcher(path);
    }

    private void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        try
        {
            logger.InfoFormat("The Elapsed event was raised at '{0:HH:mm:ss}'", e.SignalTime);
            timerTaskSuccess = true;
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Error ocurred while catching event the timer: '{0}'", ex);
            timerTaskSuccess = false;
        }
        finally
        {
            if (timerTaskSuccess)
            {
                timer.Start();
            }
        }

    }


    public void CloseTimer()
    {
        try
        {
            timer.Enabled = false;
            timer.Stop();
            timer.Dispose();
            timer = null;

            timerTaskSuccess = true;
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Error ocurred while stopping the timer: '{0}'", ex);
        }

    }
}

Anyone could help me. I test the logical code in a console application and it's working fine. Where is the issue? Thanks!

2 个答案:

答案 0 :(得分:1)

You declare the member

private aTimer timer;

but you never actually call the constructor, like:

timer = new aTimer();

So in your WindowsService.StartTimer() method you get a NullReferenceException. Add the above line to your service's constructor and you should be fine.

答案 1 :(得分:-1)

调试Windows服务有两种主要方法。一个更严格,但需要更长时间;另一个是快速而简单的。

  1. 在Visual Studio中进行调试。包装所有代码,以便它可以作为Windows服务或控制台应用程序启动。有很多方法可以做到这一点,但我见过的最好的方法是在应用程序的main方法中使用条件编译。在Debug中运行时,只需执行主类。在Release中运行时,服务模式启动并且服务正常启动。

  2. 调试已安装的Windows服务。在您的应用程序中放入大量的睡眠/等待,安装后只需使用Visual Studio附加到它。如果您睡眠30秒应该有足够的时间返回Visual Studio,请转到附加菜单,找到应用程序并附加。执行将在您的断点处停止。