admin管理员组文章数量:1392054
I'm trying to create a progress indicator in my C# console application that updates on the same line, but there is a bug that I haven't been able fix. When the view reaches the bottom and starts to scroll, if I write multiple progress indicators, then they overlap and every item is updated on the last line.
This does NOT happen in the standard windows command prompt. However it does happen in all other terminals that I have tested (new windows terminal, git bash, alacritty).
I run 5 progress tasks like so:
internal class Program
{
static async Task Main(string[] args)
{
Log($"New Start at line {Console.CursorTop}");
var tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
tasks.Add(DownloadFiles(i));
}
await Task.WhenAll(tasks);
}
static async Task DownloadFiles(int itemNumber)
{
const int max = 20;
var spinner = new ProgressSpinner();
for (int j = 1; j <= max; j++)
{
spinner.Refresh($"Item {itemNumber}, {j}/{max} files.");
await Task.Delay(50);
}
}
}
and here is the ProgressSpinner
class:
class ProgressSpinner
{
private static readonly object locker = new();
private static readonly char[] spinnerChars = ['|', '/', '-', '\\'];
private int spinnerIndex = 0;
private readonly int line;
public ProgressSpinner()
{
lock (locker)
{
Console.WriteLine();
line = Console.CursorTop;
Program.Log(line);
}
}
public void Refresh(string message)
{
lock (locker)
{
int prevPos = Console.CursorTop;
Console.SetCursorPosition(0, line);
Console.Write($"{spinnerChars[spinnerIndex]} {message}");
spinnerIndex = (spinnerIndex + 1) % spinnerChars.Length;
Console.SetCursorPosition(0, prevPos);
}
}
}
Looking at the logs, I was able to figure out the cause of the problem: In cmd, Console.CursorTop represents the actual index of the line since the beginning, while in other terminals it is the index of the line if 0 is the first visible line. I get output like this in the log:
New Start at line 54
54
54
54
54
54
It is then not surprising that I get the behavior I describe. However, I'm really not sure how to fix it. I could just keep my own static index number for the progress items, but this would not work very well if I'm also using Console.WriteLine
in other places in my application and interleaving them with progress item output. Is there a general solution?
本文标签: terminalProgress bars in c console application overlappingStack Overflow
版权声明:本文标题:terminal - Progress bars in c# console application overlapping - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744782165a2624778.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论