Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

DNX Console Application Spinner Example

5.00/5 (2 votes)
13 Mar 2016CPOL1 min read 10.2K  
Simple task based spinner for a console application

Introduction

If you need a spinner 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.

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 the Task Parallel Library (TPL) and to work around the missing Console functionality, I use the \r character instead of Console.CursorLeft.

Using the Code

You can use this class in your DNX console application to implement a spinner at the beginning of a line. I use the "\r" twice, because I want the spinner character in the console output to be overwritten after it is stopped.

C#
public class ConsoleSpinner
{
    private CancellationTokenSource TokenSource { get; set; }
    private Task Task { get; set; }

    public ConsoleSpinner()
    {
        this.TokenSource = new CancellationTokenSource();
    }

    public void Start()
    {
        var token = this.TokenSource.Token;

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

                    foreach (var spinChar in spinChars)
                    {
                        Console.Write(string.Concat("\r", spinChar, "\r"));

                        System.Threading.Tasks.Task.Delay(25).Wait();
                    }
                }
            }, token);
        }
    }

    public void Stop()
    {
        this.TokenSource.Cancel();
        this.Task.Wait();
        this.Task = null;
    }
}

Use the spinner as follows:

C#
var spinner = new ConsoleSpinner();

spinner.Start();

// do something

spinner.Stop();

Points of Interest

It is fun to work 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 this will improve when more nuget packages for DNX core become available.

History

  • 13th March. 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)