1

I got something like this:

void func()
{
    int a = int.Parse(system.readline.console());
}

But I want this function to finish after 5 seconds for example, even if the user didn't insert anything. How can I do that?

I thought about something like that:

void func()
{
     System.Timers.Timer timer = new Timer();
     timer.Interval = 5000
     timer.Elapsed += SomeFunc;
     timer.Start()
     int a = int.Parse(system.console.readline());
}
void SomeFunc(object sender, EventArgs args)
{
     Thread.CurrentThread.Abort();
}

But it looks too ugly. In addition, I don't really want to abort all the threads, just break this function. I don't want to create another thread only for this function.

ZygD
  • 22,092
  • 39
  • 79
  • 102
arielttt0
  • 59
  • 2

1 Answers1

-2

this appears to work for me

var dt = DateTime.Now;
var s = string.Empty;
while ((DateTime.Now - dt).TotalSeconds < 5)
{
    if (Console.KeyAvailable)
        s += Console.ReadKey().KeyChar;
}
Dom
  • 716
  • 4
  • 11
  • can you terminate this before the 5second span? Will it give back an int? – Random Dev Apr 24 '15 at 15:39
  • 2
    This approach is not recommended. Check CPU usage and you'll see an entire core is maxing out until the 5 seconds are up because you're running thousands/millions of times around the loop doing mostly "nothing". – wardies Apr 24 '15 at 15:41