2 threads increasing a static integer
C#
if i am increasing a static by 2 different Tasks or Threads do i need to lock it?
i have this class which will be used by multiple threads at the same time, it returns a proxy to be used inside a thread but i dont want to use the same proxy at the same time with each thread, so i thought incrementing a static integer is 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
U
user1590636