0

I have a console app that logs several different logs in a loop. What i'm trying to achieve is make this console app also accept console commands, but in case i readLine, app gets blocked.

Is there any way to achieve this ? Would it require multithreading ?

I want the app to never stop processing what is doing, but in case the user types something in the console it will pick it up to proccess on the next loop.

Gabriel Slomka
  • 1,487
  • 1
  • 11
  • 24
  • Try use for user inputs another process(Task) with self console. I found link about it [link](https://stackoverflow.com/questions/15604014/no-console-output-when-using-allocconsole-and-target-architecture-x86) – Mihal By Dec 25 '20 at 20:35
  • Check this: https://www.google.com/amp/s/blog.computedcloud.com/background-services-in-net-core-console-app/amp/ – Athanasios Kataras Dec 25 '20 at 20:50

1 Answers1

0

I managed to achieve what i was looking for in an simpler way i believe, by reading console async.

I ended up with this:

 public class ConsoleReader
    {
        private Stream _consoleStream;
        private StreamReader _reader;
        private Task<string> _readTask;

        public ConsoleReader()
        {
            _consoleStream = Console.OpenStandardInput();
            _reader = new StreamReader(_consoleStream);
            _readTask = _reader.ReadLineAsync();
        }

        public bool TryReadConsoleText(out string cmd)
        {
            if(_readTask.IsCompleted)
            {
                cmd = _readTask.Result;
                _readTask = _reader.ReadLineAsync();
                return true;
            } else
            {
                cmd = null;
                return false;
            }
        }
    }
Gabriel Slomka
  • 1,487
  • 1
  • 11
  • 24