【问题标题】:how to use text based console progress bar in multithreading C#如何在多线程 C# 中使用基于文本的控制台进度条
【发布时间】:2016-12-14 06:41:44
【问题描述】:

您好,我有一个程序可以并行(在线程中)下载 + 提取文件。 它是一个控制台应用程序,我想为每个线程中的每个操作显示进度条。 例如:

文件 1 [==========35% ] 35mb of 100mb 已下载

文件 2 [====20% ] 20mb of 100mb 下载

文件1已下载,

文件 1 [=============50% ] 50% 已提取。 等等。

注意:我可以将控制台输出显示为下面的代码,但想在我的控制台应用程序中使用此进度条。

在这种情况下,我该如何使用https://gist.github.com/DanielSWolf/0ab6a96899cc5377bf54 中提出的解决方案?

public static void DownloadAndGetFiles()
    {
        try
        {
            Parallel.ForEach(FileIds, currentId =>

            { 
               int currentId = FileIds.Id 
               clientFileDownload(currentId);
            });
        }

        catch (Exception e)
        {

        }
    }

private static void clientFileDownload(int currentId)
{
    WebClient client = new WebClient();
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
    client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
    string downloadedFile = @"d:\tmp\";
    client.DownloadFileAsync(new Uri(currentId.URL), downloadedFile); //some URL
    while (client.IsBusy) { }
    string temp = ExtractAndRename(currentId);
}

private static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
   //Prints: "Downloaded 3mb of 61.46mb  (4%)"
   Console.WriteLine("Downloaded "
              + ((e.BytesReceived / 1024f) / 1024f).ToString("#0.##") + "mb"
              + " of "                 
              + ((e.TotalBytesToReceive / 1024f) / 1024f).ToString("#0.##") + "mb"
              + "  (" + e.ProgressPercentage + "%)");
}

private static string ExtractAndRename(int currentId)
{
        //using SevenZipExtractor lib http://stackoverflow.com/questions/20898794/how-to-extract-files-in-my-archive-one-by-one-using-sevenzipsharp
        SevenZipExtractor extractor = new SevenZipExtractor(@"d:\tmp\" + id.Name);
        extractor.Extracting += extractor_Extracting;
        extractor.ExtractArchive(@"d:\tmp\" + extractName[0]);
        return (@"d:\tmp\" + extractName[0]);
}

public static void extractor_Extracting(object sender, SevenZip.ProgressEventArgs p)
{
              Console.ForegroundColor = ConsoleColor.Yellow;
              Console.Write("\b\b{0}% Extracted", p.PercentDone);
              Console.ResetColor();
}

【问题讨论】:

  • 您需要记下显示下载的控制台行,并用新行更新该行

标签: c# multithreading console progress-bar progress


【解决方案1】:
  1. 为每个线程提供一个变量y,其中包含允许写入的行号。
  2. 在线程想要更​​新屏幕之前,先创建一个锁。控制台一次只能由一个线程使用。否则多个线程的结果会混淆。
  3. 将光标移动到y 指定的行并更新该行。
  4. 释放锁。

一个例子:

static private readonly object _sync = new object();

private static void UpdateProgress(int y, string item, int progress, int total)
{
    int percentage = (int)100.0 * progress / total;
    lock(_sync)
    {
        Console.CursorLeft = 0;
        Console.CursorTop = y;
        Console.Write(item + " [" + new string('=', percentage / 2) + "] " + percentage + "%");
    }
}

您可以从您的方法clientFileDownload 调用此方法,该方法必须稍作修改:

private static void clientFileDownload(int currentId, int y)

并且应该在创建这样的线程时调用:

int y = 0;
Parallel.ForEach(FileIds, currentId =>
{ 
    int currentId = FileIds.Id 
    clientFileDownload(currentId, y);
    Interlocked.Increment(ref y);
});

【讨论】:

  • 你如何确定每个线程中每次的光标位置?
  • 代码调整(未测试)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
相关资源
最近更新 更多