Search code examples
c#multithreadinginputconsole-applicationthreadpool

Pause, enter a command and resume console app


I have a C# console app that do some work and keeps printing every 4 seconds market data.

Is there a way to be able to enter a command within the refresh rate to change some parameters and make the app continue following the new input?


Solution

  • Yes you could. Let's define 2 flows, one for main running and second for waiting new read line. Using a global variable to change through the processing between 2 flows, which is:

    • Running(): Print a line from HyperParam then sleeping 4 seconds

    • Task.Run(() => ...): Starting a infinity loop for reading a new HyperParam. Each loop will go sleeping 100 ms. That mean the user has at least 40 chances within 4 seconds to change the value.

        static string HyperParam = "A";
      
        static void Running()
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine($"Running with: {HyperParam}");
                Thread.Sleep(4000);
            }
        }
      
      
        static void Main(string[] args)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    HyperParam = Console.ReadLine();
                    Thread.Sleep(100);
                }
            });
      
            Running();
        }
      

    Result:

    enter image description here