2个线程增加一个静态整数

use*_*636 4 c#

如果我通过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") };
    }
}
Run Code Online (Sandbox Code Playgroud)

根据选定的答案

if(Interlocked.Read(ref Selectionindex) < proxies.Count())
{
    Interlocked.Increment(ref Selectionindex);
}
else
{
    Interlocked.Exchange(ref Selectionindex, 0);
}

Selectionindex = Interlocked.Read(ref Selectionindex);
Run Code Online (Sandbox Code Playgroud)

cfe*_*uke 6

如果跨线程增加静态变量,最终会得到不一致的结果.而是使用Interlocked.Increment:

private void IncrementSelectionIndex() {
    Interlocked.Increment(ref Selectionindex);
}
Run Code Online (Sandbox Code Playgroud)

64位读取是原子的,但要完全支持32位系统,您应该使用Interlocked.Read

private void RetrieveSelectionIndex() {
    Interlocked.Read(ref Selectionindex);
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,或`Interlocked.Exchange(REF Selectionindex,0)`...如果你使用`-SelectionIndex`你必须使用`Interlocked.Read`是在32位系统中的安全,即使这样......可能除非你将`Interlocked.Add`放在一个锁定在任意`对象'上的锁定块内,否则仍会产生问题. (2认同)