Fix threading bugs

This commit is contained in:
Laura 2018-06-10 11:23:30 +02:00
parent 589ffbaffc
commit 47183e055c

View file

@ -4,15 +4,15 @@ using System.Threading;
namespace ProgressBarLib {
public class ProgressBar {
private volatile bool _shouldStop;
private volatile bool _shouldStop;
private volatile List<string> _msgList = new List<string>();
private volatile List<string> _errList = new List<string>();
private volatile int _lastCurr;
private volatile int _lastTotal;
private volatile string _lastMsg = "";
private volatile string _mainMsg = "";
private readonly object _lock = new object();
private volatile bool _hasStopped;
private volatile int _lastCurr;
private volatile int _lastTotal;
private volatile string _lastMsg = "";
private volatile string _mainMsg = "";
private readonly object _lock = new object();
private volatile bool _hasStopped;
public ProgressBar() {
new Thread(() => {
@ -23,8 +23,8 @@ namespace ProgressBarLib {
ClearCurrentConsoleLine();
foreach (var msg in _msgList) {
Console.WriteLine(msg.Length < Console.WindowWidth
? msg
: msg.Substring(0, Console.WindowWidth - 1));
? msg
: msg.Substring(0, Console.WindowWidth - 1));
}
_msgList.Clear();
@ -58,8 +58,8 @@ namespace ProgressBarLib {
ClearCurrentConsoleLine();
foreach (var msg in _msgList) {
Console.WriteLine(msg.Length < Console.WindowWidth
? msg
: msg.Substring(0, Console.WindowWidth - 1));
? msg
: msg.Substring(0, Console.WindowWidth - 1));
}
_msgList.Clear();
@ -81,8 +81,8 @@ namespace ProgressBarLib {
}
public void UpdateMainAdv(int curr, int total, string custCurr, string msg) {
var outMsg = $"({custCurr}/{total}) ";
var progPart = MakeProgressBar(curr, total);
var outMsg = $"({custCurr}/{total}) ";
var progPart = MakeProgressBar(curr, total);
var msgMaxLength = Console.WindowWidth - outMsg.Length - progPart.Length;
if (msgMaxLength < 0) {
@ -99,8 +99,8 @@ namespace ProgressBarLib {
outMsg += msg;
outMsg += progPart;
_lastCurr = curr;
_lastMsg = msg;
_lastCurr = curr;
_lastMsg = msg;
_lastTotal = total;
_mainMsg = outMsg;
@ -123,19 +123,21 @@ namespace ProgressBarLib {
public void Stop() {
_shouldStop = true;
while (!_hasStopped) ;
while (!_hasStopped) { }
}
private static string MakeProgressBar(int curr, int total) {
const string fullChar = "=";
if (curr > total)
curr = total;
const string fullChar = "=";
const string blankChar = "-";
var progStr = "[";
var fullCharCount = (int) (15d / total * curr);
var fullCharCount = (int) (15d / total * curr);
var blankCharCount = 15 - fullCharCount;
for (var i = fullCharCount; i > 0; i--) progStr += fullChar;
for (var i = fullCharCount; i > 0; i--) progStr += fullChar;
for (var i = blankCharCount; i > 0; i--) progStr += blankChar;
progStr += "]";