Last active
June 19, 2022 17:48
-
-
Save ATikadze/8e82a2397d66d48194e6677911e4aea6 to your computer and use it in GitHub Desktop.
C#: Animated loading in Console Application
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
| public class ConsoleSpinner | |
| { | |
| private int _counter; | |
| private bool _spinningEnabled; | |
| public ConsoleSpinner(int spinSpeed) | |
| { | |
| SpinSpeed = spinSpeed; | |
| } | |
| public int SpinSpeed { get; set; } | |
| public void StartSpinning(string prefixText) | |
| { | |
| if (_spinningEnabled) | |
| return; | |
| new Task(async () => await StartSpinningAsync(prefixText)).Start(); | |
| } | |
| private async Task StartSpinningAsync(string prefixText) | |
| { | |
| _counter = 0; | |
| _spinningEnabled = true; | |
| Console.Write(prefixText); | |
| while (_spinningEnabled) | |
| { | |
| Spin(); | |
| await Task.Delay(SpinSpeed); | |
| } | |
| } | |
| private void Spin() | |
| { | |
| _counter++; | |
| switch (_counter % 4) | |
| { | |
| case 0: | |
| Console.Write("/"); | |
| break; | |
| case 1: | |
| Console.Write("-"); | |
| break; | |
| case 2: | |
| Console.Write("\\"); | |
| break; | |
| case 3: | |
| Console.Write("|"); | |
| break; | |
| } | |
| Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); | |
| } | |
| public void StopSpinning() | |
| { | |
| _spinningEnabled = false; | |
| Console.Clear(); | |
| } | |
| } |
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
| public class Program | |
| { | |
| private static async Task Main(string[] args) | |
| { | |
| _consoleSpinner = new ConsoleSpinner(100); | |
| _consoleSpinner.StartSpinning("Loading... "); | |
| //Some code | |
| _consoleSpinner.StopSpinning(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment