1

I am currently working on a school project that requires data to be generated, processed and stored every 2 seconds. For that, I am using while(true) loop. The problem I have is allowing user to break that loop and request generated data. Generating/storing has to be a continuous process that happens in the background, so I can't ask user for input at the beginning of each iteration. I hope someone could help me out. This would be a simple example:

    int i = 0;
    List<int> list = new List<int>();
    //Console.WriteLine("Generating will continue until any key is pressed... ");

    while (true)   
    {
       i++;
       li.Add(i);

       Thread.Sleep(2000);
    }

    foreach (int i in list)
    {
      Console.Writeline(i);
    }
anchi
  • 21
  • 2
  • What context are you in here? In a UI based app you could listen for keyboard events. Otherwise simply consider 2 different apps, and let the user ctrl+c to break the auto process and run the manual one separately – Chris Schaller May 26 '21 at 00:58
  • It would help if you told us whether this was a web app, console app, WinForm or UWP app, among other possibilities. – Dour High Arch May 26 '21 at 00:59
  • @Dour: well, the code posted above _does_ include calls to `Console.WriteLine()`. Which are not illegal in other APIs per se, but do strongly suggest it's just a console app. – Peter Duniho May 26 '21 at 01:01
  • @PeterDuniho where are you going to draw the line though ;) yes its obvious but to help the community we need to tag this appropriately and only OP should provide that level of information, we should reject community edits of that nature as its making an assumption that drastically alters the potential solutions, good luck waiting for Console input in a non-console app. – Chris Schaller May 26 '21 at 01:12
  • 1
    @Chris: _"to help the community we need to tag this appropriately "_ -- yes. _"only OP should provide that level of information"_ -- yes. _"we should reject community edits of that nature"_ -- yes. My point to Dour in my previous comment is that the OP could be asked to confirm a reasonable assumption, instead of distracting them with a host of other almost-certainly inapplicable technologies. – Peter Duniho May 26 '21 at 02:42

1 Answers1

2
while(!Console.KeyAvailable)
{
    //do work
}
jjm
  • 93
  • 1
  • 7