ilay zeidman
ilay zeidman

Reputation: 2814

C# windows service within console application code after ServiceBase.Run not executed?

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?

Upvotes: 1

Views: 594

Answers (1)

ilay zeidman
ilay zeidman

Reputation: 2814

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!

Upvotes: 3

Related Questions