Last active
July 20, 2020 14:25
-
-
Save scolestock/37af19d1fe9266ec98f57ab40d700951 to your computer and use it in GitHub Desktop.
C# Console spinner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by http://www.dib0.nl/code/458-a-spinner-for-console-in-net | |
public class ConsoleSpinner | |
{ | |
/// <summary> | |
/// Displays a text spinner and ellipses until a task completes. | |
/// </summary> | |
/// <param name="task">Task to watch for completion</param> | |
/// <param name="description">Description of the work - single word</param> | |
public static void UntilTaskComplete(Task task, string description = "work") | |
{ | |
try | |
{ | |
char[] spinner = new char[] { '|', '/', '-', '\\' }; | |
Console.Write("\r\nOne moment please while we " + description + " "); | |
bool oldCursorVisibility = Console.CursorVisible; | |
Console.CursorVisible = false; | |
int spinnerCount = 0; | |
int dotCount = 0; | |
int dotPause = 0; | |
// Account for scrolling behavior at bottom of screen | |
var fudge = (Console.BufferHeight - Console.CursorTop == 1) ? 0 : 1; | |
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - fudge); | |
while (!task.IsCompleted) | |
{ | |
string spinnerText = string.Empty; | |
spinnerText = spinnerText.PadRight(dotCount, '.'); | |
spinnerText = spinnerText.PadRight(4, ' '); | |
spinnerText += spinner[spinnerCount]; | |
int x = Console.CursorLeft; | |
int y = Console.CursorTop; | |
Console.CursorLeft = (x - 5) >= 0 ? x - 5 : x; | |
Console.Write(spinnerText); | |
if (++spinnerCount > 3) | |
spinnerCount = 0; | |
if (++dotPause == 2) | |
{ | |
dotPause = 0; | |
if (++dotCount == 4) | |
dotCount = 0; | |
} | |
Thread.Sleep(100); | |
} | |
var left = Console.CursorLeft; | |
Console.CursorLeft = (left - 5) >= 0 ? left - 5 : left; | |
Console.CursorVisible = oldCursorVisibility; | |
Console.WriteLine("..." + description + " complete."); | |
} | |
catch (Exception) | |
{ | |
Console.WriteLine("Exiting spinner while task " + task.Status); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment