如果我同时使用两个不同的任务或线程来增加一个静态变量,我需要锁定它吗?
我有一个类将被多个线程同时使用,它返回一个代理以在线程内部使用,但我不希望每个线程同时使用相同的代理,所以我认为递增一个静态整数是最好的方法,您有什么建议吗?
我有一个类将被多个线程同时使用,它返回一个代理以在线程内部使用,但我不希望每个线程同时使用相同的代理,所以我认为递增一个静态整数是最好的方法,您有什么建议吗?
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);