I wrote a small service that acts like a local network server. To write a service, I completed a tutorial on MSDN how to write a service using the ServiceBase class.
But when I register and start the service, I get error messages as shown below. I get exactly two of these error messages at the beginning and when the service stops. (Example = service name).
The Example service reported an invalid current state of 0.
Here is a minimal sample of my service with all the relevant parts. The code begins by defining the enumeration and structure that was provided in the MSDN tutorial:
public enum ServiceState { SERVICE_STOPPED = 0x00000001, SERVICE_START_PENDING = 0x00000002, SERVICE_STOP_PENDING = 0x00000003, SERVICE_RUNNING = 0x00000004, SERVICE_CONTINUE_PENDING = 0x00000005, SERVICE_PAUSE_PENDING = 0x00000006, SERVICE_PAUSED = 0x00000007, } [StructLayout(LayoutKind.Sequential)] public struct ServiceStatus { public long dwServiceType; public ServiceState dwCurrentState; public long dwControlsAccepted; public long dwWin32ExitCode; public long dwServiceSpecificExitCode; public long dwCheckPoint; public long dwWaitHint; };
After that, the service code that I wrote comes down to the relevant parts:
namespace example { public partial class Service : ServiceBase { public Service() : base() { this.ServiceName = "ExampleService"; this.AutoLog = false; this.CanStop = true; this.CanShutdown = false; this.CanPauseAndContinue = false; this.CanHandlePowerEvent = false; this.CanHandleSessionChangeEvent = false; } protected override void OnStart(string[] args) { try { SetServiceState(ServiceState.SERVICE_START_PENDING, 100000);
The main entry point is simple:
static void Main(string[] args) { ServiceBase.Run(new Service()); }
As you can see, the number of error messages corresponds to the number of calls to SetServiceState . If I add additional calls, the number of error messages increases accordingly.
So, I assume that the whole problem is what I call the SetServiceStatus API, but currently I don't see the problem.
Can you spot the problem?
Anyway, is this the right way to create a service using C # and .NET?