So I have an infinite loop that runs some code and I want it to run forever until a user types an exit command. However the problem I am having is when the code reaches the ReadLine command, it stays there until it receives a valid input from the console. How can I code it so it will move on to the rest of the code and only read from the console if there is a valid input
while(true)
{
uint quit = Uint32.Parse(Console.ReadLine());
if(quit == 1){
break;
}
else{
//some other code
}
}
CodePudding user response:
You will need to use an Asynchronous library which monitors the console for keystrokes and will pipe out commands.
I would recommend becoming familiar with IAsyncEnumerable
The pattern usually is to implement some form of IAsyncEnumerable<YourApplicationEvent>
service.
Whenever you need to pipe out to the console you can have the async service yield return
a YourApplicationEvent
, while also piping out a YourApplicationEvent
whenever the user hits enter to send command.
I use a method like this usually for this type of task:
public async IAsyncEnumerable<string> ConsoleEvents([EnumeratorCancellation] CancellationToken token)
{
await using var reader = Console.OpenStandardInput();
var commandBuffer = new List<byte>();
while (!token.IsCancellationRequested)
{
var buffer = new byte[4096];
var readCount = await reader.ReadAsync(buffer, token);
var command = new string(Encoding.UTF8.GetChars(buffer, 0, readCount));
yield return command.TrimEnd();
}
}
CodePudding user response:
You're going to want to look into asynchronous programming.
Essentially, you're going to want to create a Task
that takes care of running your code in the background, and you can wait for some console input to cancel the task if needed.
Typically this is achieved by implementing a Cancellation Token, which you can update from your loop that is waiting for user input.
Here is an example app I just made that should show you how this is accomplished:
class Program
{
static void Main(string[] args)
{
// create our token source here
var cancellationTokenSource = new CancellationTokenSource();
// and get the actual cancellation token from the token source
var cancellationToken = cancellationTokenSource.Token;
// have the Task library run an async task for us, and pass in our cancellation Token
Task.Run(
async () => {
// while our task is not cancelled
while (!cancellationToken.IsCancellationRequested)
{
// perform our code
Console.WriteLine("Simulated background code.");
await Task.Delay(1000);
}
}, cancellationToken);
// say hi
Console.WriteLine("Hello World!");
// while we havent requested a cancellation we loop
while (!cancellationToken.IsCancellationRequested)
{
// wait on reading a line
var escape = Console.ReadLine();
// if that line is quit we cancel the token
if (escape == "quit")
cancellationTokenSource.Cancel();
}
Console.WriteLine("See you later.");
}
}
}