这是场景:
- 我有一个在所有线程之间共享的代理。
如果这个代理被阻塞,那么只有一个线程需要从 ProxyQueue 中取出一个代理,而不是所有线程。对于出队,我现在使用互锁,因此一次只有一个线程可以进入该函数。
private static volatile string httpProxy = "1.1.1.1"; private static int usingResource = 0; string localHttpProxy; try { HttpWebRequest oReqReview = HttpWebRequest)WebRequest.Create(url); if (IsHttpProxyDequeue) { oReqReview.Proxy = new WebProxy(httpProxy, 8998); localHttpProxy = httpProxy; } HttpWebResponse respReview = (HttpWebResponse)oReqReview.GetResponse(); DoSomthing(); } catch (Exception ex) { if (0 == Interlocked.Exchange(ref usingResource, 1)) { if (ex.Message == "The remote server returned an error: (403) Forbidden." && httpProxy == localHttpProxy) { IsHttpProxyDequeue = currentQueueProxy.TryDequeue(out httpProxy); } Interlocked.Exchange(ref usingResource, 0); } }