我有下面的代码(下面)可以正常工作,但是没有得到预期的输出。我正在尝试为处理的每个项目在控制台上打印一条线。我想在任务完成时显示完成百分比。
这是我得到的输出(前几行重复)。我不希望他们重复,所以我知道我做错了。无论我运行多少次,前几行都是相同的。是否可以使输出显示1-> 10%,2-> 20%等?
2 --> 20 % -- Bytes Read = 23971
2 --> 20 % -- Bytes Read = 23971
2 --> 20 % -- Bytes Read = 23971
3 --> 30 % -- Bytes Read = 35909
4 --> 40 % -- Bytes Read = 47872
5 --> 50 % -- Bytes Read = 59824
6 --> 60 % -- Bytes Read = 71775
7 --> 70 % -- Bytes Read = 83746
8 --> 80 % -- Bytes Read = 95701
9 --> 90 % -- Bytes Read = 107686
Elapsed Time: : 702
Press Any Key
这是我正在运行的代码
using RestSharp;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RestSharpAsyncTest
{
public class SomeItem
{
public int Id { get; set; }
public long BytesRead { get; set; }
public SomeItem(int i)
{
this.Id = i;
this.BytesRead = 0;
}
public long ProcessItem()
{
var client = new RestClient("http://www.google.com");
var request = new RestRequest("", Method.GET);
var restResponse = client.Execute(request);
return restResponse.RawBytes.Length;
}
}
public class ProgressReport
{
public int Counter { get; set; } = 0;
public long TotalBytesRead { get; set; }
public int PercentComplete { get; set; }
}
class Program
{
private static async Task DoSomethingAsync(List<SomeItem> someItems, IProgress<ProgressReport> progress)
{
/// Set up the local progress reporter
ProgressReport progressReport = new ProgressReport();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
await Task.Run(() =>
{
Parallel.ForEach(someItems, someItem =>
{
long bytesRead = someItem.ProcessItem();
progressReport.Counter++;
progressReport.PercentComplete = (progressReport.Counter * 100) / someItems.Count;
progressReport.TotalBytesRead += bytesRead;
progress.Report(progressReport);
});
});
watch.Stop();
Console.WriteLine("Elapsed Time: : {0}", watch.ElapsedMilliseconds);
}
static async Task Main(string[] args)
{
Progress<ProgressReport> pr = new Progress<ProgressReport>();
pr.ProgressChanged += Pr_ProgressChanged;
// Create some items
List<SomeItem> someItems = new List<SomeItem>();
for (int i = 1; i < 11; i++)
someItems.Add(new SomeItem(i));
await DoSomethingAsync(someItems, pr);
Console.WriteLine("Press Any Key");
Console.ReadKey();
}
private static void Pr_ProgressChanged(object sender, ProgressReport e)
{
Console.WriteLine($"{e.Counter } --> { e.PercentComplete } % -- Bytes Read = { e.TotalBytesRead }");
}
}
}
编辑: 我添加了以下内容,但仍然得到相同的结果。
public class Program
{
private static object locker = new object();
然后
lock (locker)
{
progressReport.Counter++;
progressReport.PercentComplete = (progressReport.Counter * 100) / someItems.Count;
progressReport.TotalBytesRead += bytesRead;
progress.Report(progressReport);
}
答案 0 :(得分:0)
我发现您的代码有很多问题。很奇怪。
您不应该使用Task.Run,您应该只使用Parallel.ForEach(),然后等待ProcessItem,使用其余客户端的异步方法将其重写为异步方法。
此外,您对IProgress接口的工作方式也有很大的误解。这不是同步的。它是异步的。当您调用Report()时,它实际上将一个队列项目放入线程池中以调用事件处理程序。由于您使用的是共享库,因此它将在打印内容时进行更新。
IProgress不得在多线程环境中使用共享对象进行报告!