none
Windows Service + Timer + Thread Synchronization RRS feed

  • Question

  • Hi there,

    I was hoping someone can point me in the right direction here.

    I have written a windows service that runs every minute or so and performs some work.  I'm using a System.Timers.Timer.  In the service itself, I've created a static object to lock on.  The problem is that whenever the timer_elapsed fires, the event can occur on any thread from the pool.  I thought the static object upon which I lock would prevent other threads from entering the work section of code.  Obviously my knowledge in this area is lacking.

    First, is there a "proper" way I should be attacking this problem?  Should I be implementing ISynchronizeInvoke and synchronize the timer on that?  If so, can anyone suggest what I should read so I could at least grok the help file concerning that interface?  I'm a little out of my league there.

    Thanks in advance for any help...

    Tuesday, September 9, 2008 3:26 PM

Answers

  • It's not clear what your problem is.  Is the timer's Elapsed event ignoring the lock or do you require all work to be done on one thread? 

    There's a completely different approach that avoids all these hassles.  Use a ManualResetEvent.  Start a thread in the service OnStart() method, it should enter a loop and call the MRE's WaitOne(Int32, Boolean) method.  The 1st argument gives you the timer (false for the 2nd).  In OnStop, call the MRE's Set() method.  The thread will get a True return value from WaitOne() so it knows to exit.  If it gets False, it does the job and loops.

    All work is done on one worker thread, no timer needed, no lock needed.  And you won't have a raft of thread pool threads all blocking on the lock when the job consistently takes more than one minute.

    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, September 15, 2008 7:22 AM
    Wednesday, September 10, 2008 5:02 AM
    Moderator