【发布时间】: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