Non blocking writing to console in C#

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.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article