最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

terminal - Progress bars in c# console application overlapping - Stack Overflow

programmeradmin2浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论