スタティックを2つの異なるタスクまたはスレッドで増やしている場合、それをロックする必要がありますか?
複数のスレッドで同時に使用されるこのクラスがあり、スレッド内で使用されるプロキシを返しますが、各スレッドで同時に同じプロキシを使用したくないので、静的整数をインクリメントすることを考えました最善の方法です、何か提案はありますか?
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") };
}
}
選択した回答に基づく
if(Interlocked.Read(ref Selectionindex) < proxies.Count())
{
Interlocked.Increment(ref Selectionindex);
}
else
{
Interlocked.Exchange(ref Selectionindex, 0);
}
Selectionindex = Interlocked.Read(ref Selectionindex);