I’ve been looking all over for this,
but I just can’t seem to shake any
documentation out of the MSDN or from
Google. I’ve reviewed every .NET
article on developing Windows Services
in the MSDN I’ve located.
I’m developing a Windows Service
application. This service reads its
configuration data from the system
registry (HKLM) where it was deposited
by another “manager” application. No
The service uses a worker thread to do
its work. The thread is created in the
OnStart() and signaled/joined/disposed
in the OnStop(). Again, no problems.
Everything works beautifully when:
- The system administrator has set up everything properly, and
- the foreign network resources are all reachable.
But of course, we as developers simply
can’t rely on:
- The system administrator having set up everything properly, or
- the foreign network resources being reachable.
Really, what we need is for the
service application to have some way
of dying on its own. If a network
resource goes down, we need the
service to stop. But more to the
point, we need the SCM to know it has
stopped on its own accord. SCM needs
to know that the service has
“failed”…and hasn’t just been shut
down by someone.
Calling “return” or throwing an
exception in the “OnStart()” method
isn’t even helpful for services still
in the start-up process.. The SCM goes
merrily on and the process keeps
running in the Task Manager–though
it’s not actually doing anything since
the worker thread was never created
Using a ServiceController instance
doesn’t do it, either. That appears to
the SCM as a normal shutdown–not a
service failure. So none of the
recovery actions or restarts happen.
(Also, there is MSDNful documentation
warning about the perils of a
ServiceBase descendant using a
ServiceController to make things
happen with itself.)
I’ve read articles where people were
messing about with PInvoking calls to
the native code just to set the
“Stopped” status flag in the SCM. But
that doesn’t shut down the process the
service is running within.
I’d really like to know the Intended
- Shutting down a service from within the service, where
- The SCM is appropriatedly notified that the service has “Stopped”, and
- The process disappears from the Task Manager.
Solutions involving ServiceControllers
don’t seem to be appropriate, if only
because 2 is not satisfied. (That the
Framework documentation specifically
contraindicates doing that carries a
good deal of weight, incidentally.)
I’d appreciate any recommendations,
pointers to documentation, or even
well-reasoned conjecture. 🙂 Oh! And
I’m perfectly happy to entertain that
I’ve missed the point.
在托管代码中，您可以通过通过the ServiceBase.ServiceHandle Property和P /调用Win32 API获取SCM句柄来实现相同的效果。
我不明白为什么SCM会对待这任何不同的设置ServiceBase.ExitCode属性非零，然后调用ServiceBase.Stop，实际上。 P / Invoke有点更直接，如果服务是在恐慌模式。
转载请明显位置注明出处：c# – Windows服务失败的正确方法是什么？