XikiryoX
XikiryoX

Reputation: 1928

Windows Service - Crashes At Startup

I have built a windows Service to monitor a few settings on our servers, I have developed quite a few WinForm and WPF apps but I am an absolute newbie when it comes to Windows Services, which is why I resorted to msdn and followed the tutorial on how to create a simple service. Now I can install the service just fine and make it run, but only if I cut some bits and pieces out of the microsoft tutorial.. but I am curious why, when I follow the tutorial, my service gets an unexpected error at startup.

After some testing it seems that the service seems to crash in the onstart method at SetServiceStatus()

public partial class MyService: ServiceBase
{
    private static ManualResetEvent pause = new ManualResetEvent(false);

    [DllImport("ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
    public static extern bool SetServiceStatus(IntPtr hServiceStatus, SERVICE_STATUS lpServiceStatus);
    private SERVICE_STATUS myServiceStatus;

    private Thread workerThread = null;
    public MyService()
    {
        InitializeComponent();
        CanPauseAndContinue = true;
        CanHandleSessionChangeEvent = true;
        ServiceName = "MyService";
    }
    static void Main()
    {
        // Load the service into memory.
        System.ServiceProcess.ServiceBase.Run(MyService());
    }

    protected override void OnStart(string[] args)
    {
        IntPtr handle = this.ServiceHandle;
        myServiceStatus.currentState = (int)State.SERVICE_START_PENDING;
        **SetServiceStatus(handle, myServiceStatus);**
        // Start a separate thread that does the actual work.
        if ((workerThread == null) || ((workerThread.ThreadState & (System.Threading.ThreadState.Unstarted | System.Threading.ThreadState.Stopped)) != 0))
        {
            workerThread = new Thread(new ThreadStart(ServiceWorkerMethod));
            workerThread.Start();
        }
        myServiceStatus.currentState = (int)State.SERVICE_RUNNING;
        SetServiceStatus(handle, myServiceStatus);
    }
 }

Now my service seems to run just fine when I comment out the SetServiceStatus() lines. Why does this fail? Is this a rights-issue or am I completely missing the point here?

Upvotes: 2

Views: 2942

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564631

In general, you shouldn't have to call SetServiceStatus when implementing a managed service using the framework.

That being said, if you do call it, you need to fully initialize the SERVICE_STATUS before using it. You're currently only setting the state, but none of the other variables.

This is suggested in the best practices for SetServiceStatus: "Initialize all fields in the SERVICE_STATUS structure, ensuring that there are valid check-point and wait hint values for pending states. Use reasonable wait hints."

Upvotes: 4

Related Questions