Skip to content

Instantly share code, notes, and snippets.

@Rudde
Created October 7, 2020 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rudde/51b709894a9170b4c13cb4d99f6287c9 to your computer and use it in GitHub Desktop.
Save Rudde/51b709894a9170b4c13cb4d99f6287c9 to your computer and use it in GitHub Desktop.
Will display a pleasant spinner in your C# console apps.
public class ConsoleSpinner : IDisposable
{
private const string Sequence = @"/-\|";
private int counter = 0;
private readonly int? left;
private readonly int? top;
private readonly int delay;
private bool active;
private readonly Thread thread;
private readonly ConsoleColor? color;
private readonly ConsoleColor originalColor;
public ConsoleSpinner(int? left = null, int? top = null, int delay = 100, ConsoleColor? color = null)
{
this.left = left;
this.top = top;
this.delay = delay;
this.originalColor = Console.ForegroundColor;
this.color = color;
thread = new Thread(Spin);
}
public void Start()
{
active = true;
if (!thread.IsAlive)
thread.Start();
}
public void Stop()
{
active = false;
Draw(' ');
}
private void Spin()
{
while (active)
{
Turn();
Thread.Sleep(delay);
}
}
private void Draw(char c)
{
Console.SetCursorPosition(left ?? ((Console.CursorLeft - 1) > 0 ? Console.CursorLeft - 1 : 1), top ?? Console.CursorTop);
if (color != null)
Console.ForegroundColor = (ConsoleColor)color;
Console.Write(c);
}
private void Turn()
{
Draw(Sequence[++counter % Sequence.Length]);
}
public void Dispose()
{
Stop();
Console.ForegroundColor = originalColor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment