Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.WriteLine() inside a Windows Service?

I am currently using TopShelf with a Console Application to create a Windows Service. When I run the code as a console application I use a few Console.WriteLine() to output results. Once the code does what it is supposed to do I install the console application as a Windows Service.

Are there any downsides with leaving the Console.WriteLine() code even though a Windows Service can not write to the console? Are there any risks of having unstable code if I leave the Console.WriteLine() in there?

like image 220
Thomas Avatar asked Jan 09 '12 18:01

Thomas


People also ask

Can I run console app as Windows service?

NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.

Can you create windows service using C#?

Go to Visual C# and select Classic Desktop and from the next window, choose Windows Service. Name the service “MyFirstWindowsService” and click to OK. It will add a Windows Service for you. Rename the Service1.

What is the use of Windows service in C#?

A Windows service is a long-running application that can be started automatically when your system is started. You can pause your service and resume or even restart it if need be. Once you have created a Windows service, you can install it in your system using the InstallUtil.exe command line utility.

Where does console WriteLine go in Visual Studio?

In Visual Studio uppermost menu choose Debug > Windows > Output. It shows all Console. WriteLine("Debug MyVariable: " + MyVariable) when you get to them.


1 Answers

The output will simply be discarded.

In a Windows Service there is no Console so Console.Write* output is discarded. There are a number of alternatives:

  1. The System.Diagnostics.Trace class has a similar interface to the Console class so you could migrate your code quite easily to this.
  2. It can then be configured to output to a file. You can use the System.Diagnostics.EventLog class to write to the Event Log which you can then monitor using Event Viewer.
  3. You can use the third-party open-source log4net library which is very flexible.
like image 195
dtech Avatar answered Oct 08 '22 20:10

dtech