简体   繁体   中英

How can a service control its own state?

I have a standard windows server that inherits from the ServiceBase class.

On the OnStart method I want to check for certain conditions before I get to the main purpose of what my service does.

For example:

protected override void OnStart(string[] args)
{
  if (condition == false)
  {
    EventLog.WriteEntry("Pre-condition not met, service was unable to start");

    // TODO: Convert service state to "Stopped" because my precondition wasn't met
    return;
  }

  InnitializeService();
}

Anybody have a good example for how a service can control its own state?

Throw an Exception. This will cause the services MMC to get an error - and the exception message and stack will automatically be logged to the event log. I use ApplicationException in this case.

In addition, the service will return to the "not running" state.

If you need to stop later on, you can call the Stop method on your ServiceBase.

The error shown the user in the "Computer Management" MMC app does not seem to get the exception text correctly in Vista. It shows the following:

The "your service name here" service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.

However it writes correctly to the Event Log just fine.

Very Cool. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM