Resolved What ends a console program, if a child task is still running?

BloodyBeginner21

New member
Joined
Sep 30, 2021
Messages
2
Programming Experience
Beginner
Hi all,

I usually have GUI applications. Recently I did, in the process of learning how to deal with socket programming, come across a console program like this:

C#:
    class Program
    {
        static void Main(string[] args)
        {
            var echo = new EchoServer();

            echo.Start();

            Console.WriteLine("Server running");
            Console.ReadLine();
        }

    }


    public class EchoServer
    {
        public void Start(int port = 9999)
        {
[...]
            Task.Run(() => DoEcho(socket));
        }
        
        [...]

        private async Task DoEcho(Socket socket)
        {
            do
            {
[...]
            } while (true);
        }

I was a bit baffled when I noticed, that this program does not end with the return from the Main routine, but do the WriteLines and then continue running. Usually command line programs end with the last code line in main(). What's the mechanism which keeps the program alive, and how would it eventually end? Would it end if the infinite loop in DoEcho would be left (e.g. using break), and/or is there a discrete exit command (System.Environment.Exit(...)?) , and if so, would I have to write this command at the end of the DoEcho task, of would terminating the last active task also terminate the program?
 
Top Bottom