如果我通过 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);