2010-10-21 91 views

回答

7

通过保持一个计数器,而不是预计,该指数在哪里?例如:

int counter = 0; 
Parallel.For(4, 500, i => { 
    // TODO: something useful...   
    int progress = Interlocked.Increment(ref counter); 
    Console.WriteLine("{0}: {1}", progress, i); 
}); 

(该Interlocked的使用是必不可少的,以避免在访问counter让比赛条件)

+0

和[这里](https://gist.github.com/0xorial/8b82594e8f2b96beae77)是一样的包装。 – ironic 2014-11-24 09:21:05

3
int progress = 0; 
Parallel.For(from, to, i => { 
// do the job 
Interlocked.Increment(ref progress); 
}); 

现在实际进度(float)(to - from)/progress

+0

没有办法不使用线程同步干扰得到这个值? – abenci 2010-10-21 10:18:18

+0

@devdept no。但使用这种方法的问题是什么? – Andrey 2010-10-21 11:26:54

+0

我以为Parallel.For()包含了一个更优雅的方式来获得这个值。 – abenci 2010-10-21 14:04:51