Created
April 15, 2025 19:56
-
-
Save AldeRoberge/46f9eefb3659d359638dced2c4ce4273 to your computer and use it in GitHub Desktop.
Just a cute little spinner that looks great ππ
This file contains hidden or 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
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's how to use :
spinner.mp4
It looks way better in person, I promise! π€