Alex Rivera | Logout

System.Threading.Timer not firing after some time

Asked 2010-09-03T12:47:25.543
31

I have a windows service application. And debugging it by running in console mode.

Here http://support.microsoft.com/kb/842793 it is written that Timers.Timer has a bug and not firing in windows services. And workaround is to use Threading.Timer And this article is for .NET 1.0 and 1.1

I am using .NET 4 but after some time Threading.Timer also doesn't fire. So what can be the reason for this? And what can you suggest as a workaround?

Edit
Report

1 Answer

0

Complete example of a windows service using enterprise library for logging and recurrent threads. Remove logger.write lines if not using entreprise library

namespace Example.Name.Space
{
public partial class SmsServices : ServiceBase
{
    private static String _state = "";        
    private ManualResetEvent _stop = new ManualResetEvent(false);
    private static RegisteredWaitHandle _registeredWait;
    public WindowsServices()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {                        
        Logger.Write("Starting service", LoggerCategory.Information);            
        _stop.Reset();
        _registeredWait = ThreadPool.RegisterWaitForSingleObject(_stop,
            PeriodicProcess, null, 5000, false);

    }

    protected override void OnStop()
    {            
       // UpdateTimer.Stop();
        _stop.Set();
        Logger.Write("Stopping service", LoggerCategory.Information);
    }        
    private static void PeriodicProcess(object state, bool timedOut)
    {

        if (timedOut)
        {
            // Periodic processing here
            Logger.Write("Asserting thread state", LoggerCategory.Debug);
            lock (_state)
            {
                if (_state.Equals("RUNNING"))
                {
                    Logger.Write("Thread already running", LoggerCategory.Debug);
                    return;
                }
                Logger.Write("Starting thread", LoggerCategory.Debug);
                _state = "RUNNING";
            }
            Logger.Write("Processing all messages", LoggerCategory.Information);
            //Do something 
            lock (_state)
            {
                Logger.Write("Stopping thread", LoggerCategory.Debug);
                _state = "STOPPED";
            }
        }
        else
            // Stop any more events coming along
            _registeredWait.Unregister(null);


    }
    }
}
answered 2011-07-13T15:02:04.180

Your Answer