4

スタティックを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);
4

1 に答える 1

6

スレッド間で静的変数をインクリメントすると、一貫性のない結果になります。代わりにInterlocked.Incrementを使用してください:

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

64ビット読み取りはアトミックですが、32ビットシステムを完全にサポートするには、Interlocked.Readを使用する必要があります

private void RetrieveSelectionIndex() {
    Interlocked.Read(ref Selectionindex);
}
于 2013-03-13T03:40:40.397 に答える