2 streams incrementing a static integer

if I increase the static by 2 different tasks or threads, do I need to block it?

I have this class that will be used by several threads at the same time, it returns a proxy server that will be used inside the stream, but I do not want to use the same proxy at the same time with each thread, so I thought about incrementing a static integer - the best way , any 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 a web proxy public static WebProxy GetProxy() { Selectionindex = Selectionindex < proxies.Count()?Selectionindex++:0; return new WebProxy(proxies[Selectionindex]) { Credentials = new NetworkCredential("xxx", "xxx") }; } } 

based on the selected answer

 if(Interlocked.Read(ref Selectionindex) < proxies.Count()) { Interlocked.Increment(ref Selectionindex); } else { Interlocked.Exchange(ref Selectionindex, 0); } Selectionindex = Interlocked.Read(ref Selectionindex); 
+4
source share
1 answer

If you increment a static variable in threads, you will get inconsistent results. Use Interlocked.Increment instead:

 private void IncrementSelectionIndex() { Interlocked.Increment(ref Selectionindex); } 

64-bit reads are atomic, but for full support for 32-bit systems you should use Interlocked.Read

 private void RetrieveSelectionIndex() { Interlocked.Read(ref Selectionindex); } 
+6
source

Source: https://habr.com/ru/post/1468879/


All Articles