2017-01-19 51 views
0

我有一些过程,按顺序遍历一组大文件,并从它们中提取信息来写\更新我们的数据库。这些文件通常每行有几千行,因此我构建了一个Parallel.ForEach在给定文件中同时处理多行(由于需要按顺序应用每个文件,因此一次只处理一个文件)。现在我需要知道大概当前文件已处理了多少,以便我可以向管理层指示剩余运行时间。到目前为止,我有以下如何获得%的Parallel.ForEach完成

public void MyProcess(FileItem file) 
{ 
    List<string> lines = file.GetLines(); //some process to get the lines to handle 
    long cntr = 0; //The counter to track 

    Parallel.ForEach(lines, crntLine => 
    { 
     Console.Writeline(String.Format("Currently finished {0} out of {1} lines",cntr,lines.Count()); 
     InterLocked.Increment(ref cntr); 

     //...Code to process crntLine here 

    }); 
} 

我不在乎在所有关于该行已被处理,只有一共有多少,这样可以回答的一起是在当前文件多远的问题。这是否会给我可靠的要求?

回答

3

Interlocked.Increment会安全地将您的计数器增加为原子操作。

但是,如果你想完成线的计数,则需要行处理后增加它,而不是之前:

public void MyProcess(FileItem file) 
{ 
    List<string> lines = file.GetLines(); //some process to get the lines to handle 
    long cntr = 0; //The counter to track 

    Parallel.ForEach(lines, crntLine => 
    { 
     //...Code to process crntLine here 

     InterLocked.Increment(ref cntr); 
     Console.Writeline(String.Format("Currently finished {0} out of {1} lines",cntr,lines.Count()); 
    }); 
} 

如果您所需的百分比,除以全部完成计数计数,然后乘以100:

double percentage = (double)cntr/lines.Count * 100 
+0

看来我不能接受5分钟的答案,但这给了我我需要的东西。谢谢! – Rocky

+0

我遇到了一个障碍。我确实需要百分比,但按照您的建议,我的答案似乎总是“0.00%”。这里是我使用'double percentDone =(lineCount/results.Count())* 100的实际代码行;'发生了什么事? – Rocky

+0

@Rocky它是'cntr * 100/lines.Count' – Rabban

相关问题