简体   繁体   中英

How is code executed in a window service?

I was asked to develop a C# windows service. However I am used to create GUI with User Input.

Since windows services are automated, I would like to know how is the code executed.

I mean how can I control the flow?

Could someone clarify? I don't find a lot of information about window services...

Windows service starts exection from OnStart, usually a repeated execution starts from here could be a timer for instance. When service stops OnStop method is called. This article could be a good starting point.

protected override void OnStart(string[] args)
  {
    base.OnStart(args);

    //TODO: place your start code here
  }

  protected override void OnStop()
  {
    base.OnStop();

    //TODO: clean up any variables and stop any threads
  }

The code is started in the OnStart()

protected override void OnStart(string[] args)
{
    // Equivalent of Main()
    // Run threads here before timeout so OS knows it has started
}

Which you usually start a thread from to another function so that OnStart() can return and the service can start.

Same with OnStop and OnShutdown etc, where you would clean everything up.

protected override void OnStart(string[] args)
    {
        try
        {
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();

            serviceThread = new Thread(new ThreadStart(Delete));
            clientCleanupThread = new Thread(new ThreadStart(removeExpirery));
            enableAutoSubscribeProduct = new Thread(new ThreadStart(Products));

            serviceThread.Start();
            clientCleanupThread.Start();


            enableAutoSubscribeProduct.Start();


        }
        catch (Exception ex)
        {

            Log.Error("Error on thread start " + ex.Message);
        }
    }

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