c# - 2 threads increasing a static integer -


if increasing static 2 different tasks or threads need lock it?

i have class used multiple threads @ same time, returns proxy used inside thread dont want use same proxy @ same time each thread, thought incrementing static integer best way, suggestions?

class proxymanager {     //static variabl gets increased every time getproxy() gets called     private static int selectionindex;     //list of proxies     public static readonly string[] proxies = {};     //returns web proxy     public static webproxy getproxy()     {       selectionindex = selectionindex < proxies.count()?selectionindex++:0;       return new webproxy(proxies[selectionindex]) { credentials = new networkcredential("xxx", "xxx") };     } } 

based on selected answer

if(interlocked.read(ref selectionindex) < proxies.count()) {     interlocked.increment(ref selectionindex); } else {     interlocked.exchange(ref selectionindex, 0); }  selectionindex = interlocked.read(ref selectionindex); 

if increment static variable across threads end inconsistent results. instead use interlocked.increment:

private void incrementselectionindex() {     interlocked.increment(ref selectionindex); } 

64-bit reads atomic, support 32-bit systems should use interlocked.read

private void retrieveselectionindex() {     interlocked.read(ref selectionindex); } 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -