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);
source share