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:
- Which Worker is better suited for my purpose: a Thread or a LongRunning Task ?
- How to check for the Workers status in OnStart without using a looped Worker function?
- How to handle an exception from the MyDataLogger class to change the status and restart the Worker?
- 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!