c# – How to make a console application that runs endlessly in the background and reacts to events?

Question:

Only looping main can solve this problem or is there a more beautiful solution?

Answer:

The essence of the application is the execution of the Main function while this application should be running. Accordingly, if the application must run forever, then not leaving the Main method is the only correct and absolutely natural solution.

Don't be fooled by platforms like Windows.Forms – ultimately your code is rooted in the .NET Main method, which is rooted in the input address in the header of the executable. When the function finishes executing, the axis considers the process completed.

From an implementation point of view, of course, you shouldn't do while (true) Thread.Sleep(1) , instead, you should normally wait for events that the application should respond to. For example, if the application must respond to console input, then in the loop you can read Console.ReadLine() – this function will stop execution without devouring processor time and return the line when it is.

True, in Windows "eternally running applications" are usually made services. The service is registered in the system list of services, receives the means to control user execution, the axis monitors the start and operation of the service, etc. The console is convenient only for debugging, because you can output the log directly to the console for clarity. If the application needs to closely interact with the user, you can also make an icon in the notification area.

Scroll to Top