C # Convert Console Application to Service

I am trying to convert a console application to a windows service. I am trying to have the onstart method of the service call the method in my class, but I cannot get it to work. I'm not sure I'm doing it right. Where do I put class information in a service

protected override void OnStart(string[] args) { EventLog.WriteEntry("my service started"); Debugger.Launch(); Program pgrm = new Program(); pgrm.Run(); } 

From the comment:

 namespace MyService { static class serviceProgram { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); } } } 
+7
c # console service onstart
source share
2 answers

The MSDN documentation on Windows Services is really good and has everything you need to get started.

The problem you are facing is related to your OnStart implementation, which should only be used to configure the service so that it is ready to start, the method should immediately return. Usually you run the bulk of the code in another thread or timer. Check the OnStart page for confirmation.

Edit: Not knowing what your Windows service will do, it's hard to say how to implement it, but let me say that you want to run the method every 10 seconds while the service is running:

 public partial class Service1 : ServiceBase { private System.Timers.Timer _timer; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { #if DEBUG System.Diagnostics.Debugger.Launch(); // This will automatically prompt to attach the debugger if you are in Debug configuration #endif _timer = new System.Timers.Timer(10 * 1000); //10 seconds _timer.Elapsed += TimerOnElapsed; _timer.Start(); } private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) { // Call to run off to a database or do some processing } protected override void OnStop() { _timer.Stop(); _timer.Elapsed -= TimerOnElapsed; } } 

Here, the OnStart method returns immediately after setting the timer, and TimerOnElapsed will be executed in the TimerOnElapsed . I also added a call to System.Diagnostics.Debugger.Launch(); which will facilitate debugging.

If you have other requirements, edit your question or post a comment.

+8
source share

Do yourself the greatest service and use topshelf http://topshelf-project.com/ to create your service. There is nothing easier than I saw. Their documentation is supperb, and deployment couldn't be simpler. c: / service path /service.exe install.

+2
source share

All Articles