Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# windows services program

I was able to create a simple windows service app. just the frame. but I am still confused. where should I put my code for the windows service to actually do something. I have a separate program that I would like to include/call/incorporate here. where should put the program? where should I start?

public partial class MyNewService : ServiceBase
{
    public MyNewService()
    {
        InitializeComponent();
        if (!System.Diagnostics.EventLog.SourceExists("MySource"))
        {
            System.Diagnostics.EventLog.CreateEventSource(
                "MySource", "MyNewLog");
        }
        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";
    }




    static void Main()
    {
        System.ServiceProcess.ServiceBase[] ServicesToRun;
        // Change the following line to match.
        ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyNewService() };
        System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    }
}

}

like image 646
John Ryann Avatar asked Jul 16 '26 20:07

John Ryann


1 Answers

You need to override the OnStart method (and other similar ones, such as OnStop, OnShutdown, etc).

When you do this, make sure that your OnStart method does not block or take very long to execute. This often means running your actual service logic in its own thread.

like image 133
Reed Copsey Avatar answered Jul 19 '26 10:07

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!