Problem with timer in service

R

r norman

Please excuse the cross-posting. This question was raised in
microsoft.public.dotnet.general but hasn't been answered so I am
trying where I can.

There are two of us who have the same problem in a service: the
Timer::Tick event processor never gets called. We have set the timer
interval, enabled it, and started it, but still nothing.

In my case, I also have enabled an event handler to detect
SessionSwitch, but that never gets called either. Yes, I enabled the
CanHandleSessionChangeEvent property. My event processors write to a
log file, as do OnStart and OnStop service events but only the latter
log entries ever appear. My timer code works perfectly well in a form
program, but not my service.

I am new to dotNet programming so I don't understand what is behind
the scenes. No doubt I (we) are neglecting something simple. For
example, I know that in ordinary Win32 programming, responding to a
timer or to session events requires a window (albeit invisible in a
service) with a message pump, something that a service would not
ordinarily have. Is that the problem?

How do you use a timer in a service?
 
C

Carl Daniel [VC++ MVP]

Greg Young said:
I have heard of lots of flakey timer behaviors in services.

System.Windows.Forms.Timer won't work in any context which lacks a message
loop since it's based on WM_TIMER message handling. Most services lack a
message loop.
In nearly all cases uses System.Threading.Timer
http://www.dotgnu.org/pnetlib-doc/System/Threading/Timer.html fixed the
issues.

That would be appropriate for most uses in a service. Of course, you have
to be careful using System.Threading.Timer because the timer events will be
raised in a different thread from the one that started the timer. This may
cause problems even outside the Windows Forms/GUI environment if you haven't
made things thread-safe.

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top