C# Console.Readline Non Blocking Assignment

Write message to console without blocking current thread

The fast and most commonly used method to debug code is for sure using console applications. Since main operations are reading input and writing output, it does not take much to set it up and start debugging your code.

One more reason for using console application is to test the performance. How ever writing to console is not an async operation meaning the code is block while doing Console.WriteLine.

Of course, this blocking is not that long and there is no major delay in your code, but in case you set console output to something else rather than display which is default, your code might get higher delay which might affect testing results of the code you are testing.

Console.SetOut(new StreamWriter(new FileStream("C:\Temp\MyFile.txt", FileMode.CreateNew)) { AutoFlush=true});

To resolve this issue there needs to be a workaround implemented, so that writing of console is done in a separate thread rather than doing it on the main thread of the application.

public static class ConsoleWriter { private static BlockingCollection<string> blockingCollection = new BlockingCollection<string>(); static ConsoleWriter() { Task.Run(() => { while (true) { System.Console.WriteLine(blockingCollection.Take()); } }); } public static void WriteLine(string value) { blockingCollection.Add(value); } }

Since System.Console is a static class, we cannot inherit it or do any elegant solution. Instead we can only wrap it in a new static class.

In the code above, writing to console is moved from the main thread to a separate Task/Thread which will run in the background and pick the values from the BlockingCollection. This way, writing out to console output will be handled away from main thread avoiding any code delay while writing to what ever the Console output is set to.

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

The ReadLine method reads a line from the standard input stream. (For the definition of a line, see the paragraph after the following list.) This means that:

  • If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.

    One of the most common uses of the ReadLine method is to pause program execution before clearing the console and displaying new information to it, or to prompt the user to press the Enter key before terminating the application. The following example illustrates this.

    using System; publicclass Example { publicstaticvoid Main() { Console.Clear(); DateTime dat = DateTime.Now; Console.WriteLine("\nToday is {0:d} at {0:T}.", dat); Console.Write("\nPress any key to continue... "); Console.ReadLine(); } } // The example displays output like the following:// Today is 10/26/2015 at 12:22:22 PM.// // Press any key to continue...
  • If standard input is redirected to a file, the ReadLine method reads a line of text from a file. For example, the following is a text file named ReadLine1.txt:

    The following example uses the ReadLine method to read input that is redirected from a file. The read operation terminates when the method returns null, which indicates that no lines remain to be read.

    After compiling the example to an executable named ReadLine1.exe, you can run it from the command line with the syntax

    to read the contents of the file and display them to the console.

    This is the first line. This is the second line. This is the third line. This is the fourth line.
    using System; publicclass Example { publicstaticvoid Main() { if (! Console.IsInputRedirected) { Console.WriteLine("This example requires that input be redirected from a file."); return; } Console.WriteLine("About to call Console.ReadLine in a loop."); Console.WriteLine("----"); String s; int ctr = 0; do { ctr++; s = Console.ReadLine(); Console.WriteLine("Line {0}: {1}", ctr, s); } while (s != null); Console.WriteLine("---"); } } // The example displays the following output:// About to call Console.ReadLine in a loop.// ----// Line 1: This is the first line.// Line 2: This is the second line.// Line 3: This is the third line.// Line 4: This is the fourth line.// Line 5:// ---
    ReadLine1 < ReadLine1.txt

A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine property. The returned string does not contain the terminating character(s). By default, the method reads input from a 256-character input buffer. Because this includes the Environment.NewLine character(s), the method can read lines that contain up to 254 characters. To read longer lines, call the OpenStandardInput(Int32) method.

The ReadLine method executes synchronously. That is, it blocks until a line is read or the Ctrl+Z keyboard combination is pressed. The In property returns a TextReader object that represents the standard input stream and that has both a synchronous TextReader.ReadLine method and an asynchronous TextReader.ReadLineAsync method. However, when used as the console's standard input stream, the TextReader.ReadLineAsync executes synchronously rather than asynchronously and returns a Task<String> only after the read operation has completed.

If this method throws an OutOfMemoryException exception, the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read, but the characters already read into the internal ReadLine buffer are discarded. Since the position of the reader in the stream cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the TextReader. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream also needs to be reinitialized. To avoid such a situation and to produce robust code, you should use the KeyAvailable property and ReadKey method and store the read characters in a pre-allocated buffer.

If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null. This enables the user to prevent further keyboard input when the ReadLine method is called in a loop. The following example illustrates this scenario.

using System; publicclass Example { publicstaticvoid Main() { string line; Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):"); Console.WriteLine(); do { Console.Write(" "); line = Console.ReadLine(); if (line != null) Console.WriteLine(" " + line); } while (line != null); } } // The following displays possible output from this example:// Enter one or more lines of text (press CTRL+Z to exit):// // This is line #1.// This is line #1.// This is line #2// This is line #2// ^Z// // >

0 thoughts on “C# Console.Readline Non Blocking Assignment

Leave a Reply

Your email address will not be published. Required fields are marked *