Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created April 15, 2025 19:56
Show Gist options
  • Save AldeRoberge/46f9eefb3659d359638dced2c4ce4273 to your computer and use it in GitHub Desktop.
Save AldeRoberge/46f9eefb3659d359638dced2c4ce4273 to your computer and use it in GitHub Desktop.
Just a cute little spinner that looks great πŸ˜ŽπŸ‘
using System.Text;
namespace ADG.ConsoleSpin;
public static class ConsoleSpinner
{
private static int counter;
private static readonly string[] SpinnerChars = ["β ‹", "β ™", "β Ή", "β Έ", "β Ό", "β ΄", "β ¦", "β §", "β ‡", "⠏"]; // Braille characters that work reliably
public static async Task RunAsync(Func<Task> task, string message = "Processing...")
{
await RunInternal(task, message);
}
private static async Task RunInternal(Delegate taskDelegate, string message)
{
// Ensure console can handle Unicode
Console.OutputEncoding = Encoding.UTF8;
Console.CursorVisible = false;
Console.Write(message);
var cancellationTokenSource = new CancellationTokenSource();
var spinnerTask = Task.Run(() =>
{
while (!cancellationTokenSource.Token.IsCancellationRequested)
{
Console.Write($"\r{message} {SpinnerChars[counter % SpinnerChars.Length]}");
Thread.Sleep(80); // Slightly faster animation
counter++;
}
cancellationTokenSource.Dispose();
}, cancellationTokenSource.Token);
try
{
await (Task)taskDelegate.DynamicInvoke();
}
finally
{
await cancellationTokenSource.CancelAsync();
try
{
await spinnerTask;
}
catch (OperationCanceledException)
{
// Ignore cancellation exceptions
}
Console.Write("\r" + new string(' ', message.Length + 2) + "\r"); // Clear the line
Console.WriteLine($"{message} Complete!");
Console.CursorVisible = true;
}
}
}
@AldeRoberge
Copy link
Author

AldeRoberge commented Apr 15, 2025

Here's how to use :

        await ConsoleSpinner.RunAsync(async () =>
        {
            await Task.Delay(5000);
            Log.Logger.LogInformation("Async operation completed.");
        }, "Waiting for database connection...");
spinner.mp4

It looks way better in person, I promise! 🀞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment