I want to make a C# Console App, that can evaluate user input while it is doing some work. For that I want to await the Input asynchron similar to this: await Console.ReadLine(). For testing purpose I simply want the main work loop to stop running when I hit Enter. I have achieved that like this:
using System;
using System.Threading;
using System.Threading.Tasks;
class WorkTillEnter
{
private static bool running = false;
public static void Main(string[] args)
{
WorkTillEnter.running = true;
WorkTillEnter.observeInputAsync();
DateTime lastTick = DateTime.Now;
while(WorkTillEnter.running){
if(lastTick.Second != DateTime.Now.Second){
Console.WriteLine($"Tick {DateTime.Now}");
lastTick = DateTime.Now;
}
//Doing Work in this loop until enter is hit
}
Console.WriteLine("Worker Terminated.");
}
private static async void observeInputAsync(){
await Task.Delay(1); // <--WHY???
await Console.In.ReadLineAsync();
WorkTillEnter.running = false;
}
}
This works fine and prints Ticks every Second until Enter is hit. My Qustion is now: Why does it not work when I delete this one Line? await Task.Delay(1); // <--WHY???
Whithout this Line the programm does nothing until I hit return, and then obviously never enters the while loop. How can this behavior be explained?
This suggestion Why does Console.In.ReadLineAsync block? explaines why Console.In.ReadLineAsync
isn't behaving as expected when my questionable Line is removed. But it does not explain why it actualy beahaves as expected when the Line is added.