SIGN UP MEMBER LOGIN:    
ARTICLE

Console Application Wait/Busy Spin Animation

Posted by Colin Articles | Visual C# December 18, 2008
Create a spinning busy animation on a background worker thread in a console applcation
Reader Level:

If you would like your console application to show a spinning animation (cycle through characters | / - \ in place) to show your application is busy/working then the following class can do that for you.

Simple run the animation using:

SpinAnimation.Start() or SpinAnimation.Start(50) depending on how fast you want your animation to spin.

To stop the animation use:

SpinAnimation.Stop()

Spin animation will deliberately throw an invalid operation when attempting to start it twice but can be checked with the Boolean ISBusy property prior to starting.  Stop can be called twice successively without any exceptions.

Here is the class which is self documented to describe how it works:

/// <summary>

/// Create spinning console busy animation runnning on a background thread

/// </summary>

 

public static class SpinAnimation

{

 

    //spinner background thread

    private static System.ComponentModel.BackgroundWorker spinner = initialiseBackgroundWorker();

    //starting position of spinner changes to current position on start

    private static int spinnerPosition = 25;

    //pause time in milliseconds between each character in the spin animation

    private static int spinWait = 25;

    //field and property to inform client if spinner is currently running

    private static bool isRunning;

 

    public static bool IsRunning { get { return isRunning; } }

 

    /// <summary>

    /// Worker thread factory

    /// </summary>

    /// <returns>background worker thread</returns>

 

    private static System.ComponentModel.BackgroundWorker initialiseBackgroundWorker()

    {

 

        System.ComponentModel.BackgroundWorker obj = new System.ComponentModel.BackgroundWorker();

        //allow cancellation to be able to stop the spinner

        obj.WorkerSupportsCancellation = true;

        //anonymous method for background thread's DoWork event

        obj.DoWork += delegate

        {

            //set the spinner position to the current console position

            spinnerPosition = Console.CursorLeft;

            //run animation unless a cancellation is pending

            while (!obj.CancellationPending)

            {

                //characters to iterate through during animation

                char[] spinChars = new char[] { '|', '/', '-', '\\' };

                //iterate through animation character array

                foreach (char spinChar in spinChars)

                {

                    //reset the cursor position to the spinner position

                    Console.CursorLeft = spinnerPosition;

                    //write the current character to the console

                    Console.Write(spinChar);

                    //pause for smooth animation - set by the start method

                    System.Threading.Thread.Sleep(spinWait);

                }

            }

        };

        return obj;

    }

 

    /// <summary>

    /// Start the animation

    /// </summary>

    /// <param name="spinWait">wait time between spin steps in milliseconds</param>

    public static void Start(int spinWait)

    {

        //Set the running flag

        isRunning = true;

        //process spinwait value

        SpinAnimation.spinWait = spinWait;

        //start the animation unless already started

        if (!spinner.IsBusy)

            spinner.RunWorkerAsync();

        else throw new InvalidOperationException("Cannot start spinner whilst spinner is already running");

    }

 

    /// <summary>

    /// Overloaded Start method with default wait value

    /// </summary>

    public static void Start() { Start(25); }

    /// <summary>

    /// Stop the spin animation

    /// </summary>

 

    public static void Stop()

    {

        //Stop the animation

        spinner.CancelAsync();

        //wait for cancellation to complete

        while (spinner.IsBusy) System.Threading.Thread.Sleep(100);

        //reset the cursor position

        Console.CursorLeft = spinnerPosition;

        //set the running flag

        isRunning = false;

    }

}

Login to add your contents and source code to this article
share this article :
post comment
 

The example was a small one at the top: To start the spinner: if(!SpinAnimation.IsBusy) SpinAnimation.Start(50) //where 50 is the num of milliseconds between each spin step To stop the spinner: SpinAnimation.Stop(50) It is then up to your application's logic to start and stop the spinner based on whether or not the application is busy. for most of the time it will be a case of surrounding the code with a start and stop.

Posted by Colin Dec 22, 2008

Please provide example how to use your class.

Posted by Gregory Suvalia Dec 19, 2008
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor