如果我通过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);
答案 0 :(得分:6)
如果跨线程增加静态变量,最终会得到不一致的结果。而是使用Interlocked.Increment:
private void IncrementSelectionIndex() {
Interlocked.Increment(ref Selectionindex);
}
64位读取是原子的,但为了完全支持32位系统,您应该使用Interlocked.Read
private void RetrieveSelectionIndex() {
Interlocked.Read(ref Selectionindex);
}