简体   繁体   中英

Windows Service executes code in debug, but not in release

I'm working on a Windows Service that hosts a WCF-webservice, which works when I run it in debug mode:

#if DEBUG
        SynchroService myService = new SynchroService();
        myService.OnDebugStart();
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new SynchroService() 
            };

            ServiceBase.Run(ServicesToRun);

#endif

The OnDebugStart() just calls the OnStart() method of the Windows service and the thread that runs is just a thread that runs infinitely (untill the OnStop() is called) to check if the service is still alive & online.

        protected override void OnStart(string[] args)
    {
        try
        {
            ServiceStatus serviceStatus = new ServiceStatus();
            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            syncService = new SynchroComService();
            myServiceHost = new ServiceHost(syncService);
            myServiceHost.Open();
            syncService.StartListening();

            thread = new Thread(CheckHost);
            thread.Start();
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

Now, when I create the WCF service (syncService), it should run code to start up SQLDependency and start listening to the database. This works perfectly fine when I start it in debugmode, but when I run it in release, the service gets hosted, but the code doesn't execute.

I've looked everywhere for an answer or problems of the same type, but I've come up with nothing. So if anyone has every come across a problem of the same type, please do tell how you solved it.

Kind regards

The problem wasn't my code, it was with the permissions when running the service.
The service was being started as local systemaccount, but it didn't have permissions to run the service/execute the code.

To change the account that runs the service:

  1. Open services.msc
  2. Right click the service name
  3. Go to the logon tab and change the account to the/an account that has the correct permissions
  4. Restart the service

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