简体   繁体   中英

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?

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!

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