1

I implemented windows service with in console application as follows:

  internal class Program
{
    private static void Main(string[] args)
    {

            ServiceBase.Run(new MyServicesInitializer()); //host the services in managed windows service

         //some more code
         string x=1;
         .....

    }



 public class MyServicesInitializer : ServiceBase
 {
       protected override void OnStart(string[] args)
       {
               //my code
       }
 }

My question is: when I start the service with sc.exe do the main method is called? it seems like not... If someone can explain the flow what is happening when I start the service with sc and for what reason I need the line: ServiceBase.Run(new MyServicesInitializer()); in my main?

Edit: I did experiment and throw exception before and after the line in the main: when I throw exception before the exception was thrown but when I put the exception after the run method it is not thrown and the service started successfully... Someone can explain why the code after the Run method is not executed?

ilay zeidman
  • 2,654
  • 5
  • 23
  • 45

1 Answers1

3

I managed to figure out what happening, here is the flow: When the function ServiceBase.Run(new MyServicesInitializer()); is called the code is not returning from this function until the service is stopped therefore the code after it will run only after the service is stopped!

ilay zeidman
  • 2,654
  • 5
  • 23
  • 45
  • I wouldn't count on that either, as it is undocumented behaviour. Safer to assume that the only thing you can do in the main function is to call `ServiceBase.Run`. – Harry Johnston Nov 16 '14 at 21:28
  • But I implemented the two modes: console mode for development and windows service mode for production... but it is important to know that when the service stop the code after it is executing... In my case after the function ServiceBase.Run I added return statement. – ilay zeidman Nov 17 '14 at 06:37