2010-10-21 95 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