0

ive got a loop that runs in the background. at the same time I need the program to register inputs by the user, and have the code react if any input happens. can I somehow do this?

So from a snippet like this-

string input = ""; 
while(true)
{
  Console.WriteLine(input);
}
input = PermanentReadLine();

id expect it to change what it writes to the screen whenever i write anything into the ReadLine

sufan02
  • 9
  • 1
  • 1
    Does this answer your question? [C# Console Application - How do I always read input from the console?](https://stackoverflow.com/questions/22899416/c-sharp-console-application-how-do-i-always-read-input-from-the-console) – GSerg May 07 '21 at 15:36
  • Are you looking for 2 different threads? one is for reading from the console and one is for writing? – sujith karivelil May 07 '21 at 15:39
  • 1
    Having something that's reading and writing to the console at the same time would be very confusing. – juharr May 07 '21 at 15:43

2 Answers2

2

You can accomplish this by having one task reading input and a separate one processing it. Here's an implementation using Channels:

async Task Main()
{
    var channel = Channel.CreateUnbounded<string>();
    var worker = Task.Run(async () =>
    {
        while (await channel.Reader.WaitToReadAsync())
            while (channel.Reader.TryRead(out var input))
                Console.WriteLine(input);
    });
    
    while (true)
    {
        var input = Console.ReadLine();
        if (input.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
        {
            channel.Writer.Complete();
            break;
        }
        channel.Writer.TryWrite(input);
    }
}

This example terminates when the user types "exit".

Eric J.
  • 147,927
  • 63
  • 340
  • 553
1
Task.Run(() => {
    while(true)
    {
       string input = Console.ReadLine();

       // Do something with the input. Maybe switch or if/else statement?
    }
});

This will still allow the rest of the program to continue.

Thomas V
  • 65
  • 10