Reputation: 1194
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);
Upvotes: 4
Views: 268
Reputation: 23236
If you increment a static variable across threads you will end up with inconsistent results. Instead use Interlocked.Increment:
private void IncrementSelectionIndex() {
Interlocked.Increment(ref Selectionindex);
}
64-bit reads are atomic, but to fully support 32-bit systems you should use Interlocked.Read
private void RetrieveSelectionIndex() {
Interlocked.Read(ref Selectionindex);
}
Upvotes: 5