DNX Console application spinner example

Introduction

If you need a spinner/busy indicator in a console application, you can find thread based examples on how to do this easily via Google or other search engines, however I could not find working spinner examples for DNX console applications. This article shows how to implement a simple spinner in a DNX console application. The spinner runs at the beginning of a console line.

Background

If you work with DNX core dependencies, you are not able to use some traditional threading techniques and console functionality. For creating a spinner I will use System.Threading.Task and to work around the missing Console functionality I use the \r character instead of Console.CursorLeft.

Code example

You can use this class in your DNX console application to implement a spinner at the beginning of a line. After the spinner is stopped, the spinner will be overwritten by any other text that is written to the console output. Optionally you can set the interval speed of the spinner at start, the default interval is 25 milliseconds.
You will need to import namespaces System, System.Threading, System.Threading.Tasks.

public class ConsoleSpinner
{
    /// <summary>
    /// CancellationTokenSource for stopping spinner task
    /// </summary>
    private CancellationTokenSource TokenSource { get; set; }
    
    /// <summary>
    /// Spinner task
    /// </summary>
    private Task Task { get; set; }

    ///<summary>
    /// Start the console spinner
    /// </summary>
    /// <param name="speedInterval">Interval for spinner rotation in milliseconds</param>
    public void Start(int? speedInterval)
    {
        var interval = speedInterval.HasValue ? speedInterval.Value : 25;

        if (this.Task == null)
        {
            this.TokenSource = new CancellationTokenSource();

            this.Task = Task.Run(() =>
            {
                while (!this.TokenSource.Token.IsCancellationRequested)
                {
                    var spinChars = new char[] { '|', '/', '-', '\\' };

                    // Start at begin of line
                    Console.Write("\r");

                    foreach (var spinChar in spinChars)
                    {
                        // Write spinner char and return to begin of line
                        Console.Write(string.Concat(spinChar, "\r"));

                        System.Threading.Tasks.Task.Delay(interval).Wait();
                    }
                }
            }, this.TokenSource.Token);
        }
    }

    /// <summary>
    /// Stop the console spinner
    /// </summary>
    public void Stop()
    {
        this.TokenSource.Cancel();
        this.Task.Wait();
        this.Task = null;
    }
}

Use the spinner as follows:

var spinner = new ConsoleSpinner();

spinner.Start();

// Do some task(s)

spinner.Stop();

 

My conclusion

I had fun working with the new DNX core framework but at this point I find myself struggling to find alternatives for techniques / namespaces that were included in the normal .NET framework. I guess that will improve when more nuget packages for DNX core become available :)

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>