如果我通过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)
如果跨线程增加静态变量,最终会得到不一致的结果.而是使用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)
| 归档时间: |
|
| 查看次数: |
242 次 |
| 最近记录: |