Parallel.For()循环中的进度更新
答
通过保持一个计数器,而不是预计,该指数在哪里?例如:
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
让比赛条件)
答
int progress = 0;
Parallel.For(from, to, i => {
// do the job
Interlocked.Increment(ref progress);
});
现在实际进度(float)(to - from)/progress
和[这里](https://gist.github.com/0xorial/8b82594e8f2b96beae77)是一样的包装。 – ironic 2014-11-24 09:21:05