0

I am pretty new to C# and Windows Services but got my first service running to log data coming from a tcp client. At the moment I just start the Logging method during OnStart

    protected override void OnStart(string[] args)
         {
            MyDataLogger DataLogger = new MyDataLogger();
            MyDataLogger.StartLogging();
         }
 

StartLogging contains some Connections to Databases and a definition of a notification on the tcp client. Up to now it works fine but I am concerned about undesired events like loosing the tcp connection. When undesired events occur I catch and log them in an error log but I am currently not able to restart the service properly. A colleague mentioned to start a separate Thread for the Logging procedure and restart it when an Exception is raised. So far I found different sources discussing several parts like Windows Service to run constantly and Restarting a thread in .NET (using C#) of the needed solution. I also like the answer of How to have a loop in a Windows service without using the Timer but dont know how to implement it for my case with a notification in the Worker Function instead of a looped request. At the moment I still have the following questions:

  1. Which Worker is better suited for my purpose: a Thread or a LongRunning Task ?
  2. How to check for the Workers status in OnStart without using a looped Worker function?
  3. How to handle an exception from the MyDataLogger class to change the status and restart the Worker?
  4. Is it correct to dispose all client/database connections during an exception and call the StartLogging again when restarting the Worker?

Thanks a lot in advance!

Andre S.
  • 478
  • 4
  • 13
  • 1
    You want to avoid during anything lengthy in `OnStart`. If you take too long Service Control Manager will report the service as _"not repsonding"_. For this reason you should place the essence of your service in a child thread. This thread represents the _main_ thread of the service. Also, if your service does take a long time to start you should send heartbeats to SCM –  Aug 25 '20 at 12:07
  • LongRunning `Task.Run()` essentially creates a Background `Thread`. But my vote for `Task`. – aepot Aug 25 '20 at 12:19

0 Answers0