using System; using System.Collections.Generic; using System.Threading; namespace ProgressBarLib { public class ProgressBar { private volatile bool _shouldStop; private volatile List _msgList = new List(); private volatile string _mainMsg = ""; private readonly object _lock = new object(); public ProgressBar() { Console.WriteLine(); new Thread(() => { Thread.CurrentThread.IsBackground = true; while (!_shouldStop) { lock (_lock) if (_msgList.Count > 0) { foreach (var msg in _msgList) { Console.WriteLine(msg); } _msgList.Clear(); } Console.Write("\r" + _mainMsg); Thread.Sleep(500); } }).Start(); } public void UpdateMain(int curr, int total, string msg) { var outMsg = $"({curr}/{total}) "; var progPart = MakeProgressBar(curr, total); var msgMaxLength = Console.WindowWidth - outMsg.Length - progPart.Length; if (msgMaxLength < 0) { _mainMsg = "Increase terminal width"; return; } if (msg.Length < msgMaxLength) for (var i = (msgMaxLength - msg.Length); i > 0; i--) msg += " "; else msg = msg.Substring(0, msgMaxLength); outMsg += msg; outMsg += progPart; _mainMsg = outMsg; } public void UpdateMainAdv(int curr, int total, string custCurr, string msg) { var outMsg = $"({custCurr}/{total}) "; var progPart = MakeProgressBar(curr, total); var msgMaxLength = Console.WindowWidth - outMsg.Length - progPart.Length; if (msgMaxLength < 0) { _mainMsg = "Increase terminal width"; return; } if (msg.Length < msgMaxLength) for (var i = (msgMaxLength - msg.Length); i > 0; i--) msg += " "; else msg = msg.Substring(0, msgMaxLength); outMsg += msg; outMsg += progPart; _mainMsg = outMsg; } public void PushMsg(string msg) { lock(_lock) _msgList.Add(msg); } public void Stop() { _shouldStop = true; } private static string MakeProgressBar(int curr, int total) { const string fullChar = "="; const string blankChar = "-"; var progStr = "["; var fullCharCount = (int) (15d / total * curr); var blankCharCount = 15 - fullCharCount; for (var i = fullCharCount; i > 0; i--) progStr += fullChar; for (var i = blankCharCount; i > 0; i--) progStr += blankChar; progStr += "]"; return progStr; } } }