Prabhu
Prabhu

Reputation: 13335

Reading random length of characters at a time

I'm trying to read a series of characters that are typed in at a time, on a console application:

  while(true)
  {     
    var input= string.Empty;
    do
    {
        var key = Console.ReadKey();    
        input += key.KeyChar;              
    }
    while (input.Length <= 5);

    //do something with input.
  }

Since there will be no carriage return, I could make this work by putting a fixed length for the input. But actually I won't know how many characters will be entered at a time...it could be anywhere from 1 - 10. Is there anyway to modify the above code so that the app can take in whatever is entered at a time? The only thing that separates different inputs is time (at least 2 or 3 seconds can be assumed), since there is no carriage return.

Upvotes: 1

Views: 61

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

So as horrible an idea as I think using a timeout to decide whether or not a user is done, you could achieve it with something like this:

var input = string.Empty;
var lockObj = new Object();
System.Threading.Timer timer = new System.Threading.Timer(o =>
{
    string localInput;
    lock(lockObj)
    {
        localInput = input;
        input = string.Empty;
    }
    Console.WriteLine("\noutput: {0}", localInput);

}, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);   
while (true)
{
    var key = Console.ReadKey();
    timer.Change(2000, System.Threading.Timeout.Infinite);
    lock(lockObj)
    {
        input += key.KeyChar;
    }
}

You start a timer (cancelling any previous one) when a key is pressed and when that timer expires (assuming it wasn't cancelled by another key press), you do something with whatever value is currently in input. Note: since you are now multithreading, you will need to worry about what that something you are doing is and whether or not it's thread-safe. You may have to lock or synchronize.

Upvotes: 5

Related Questions