シナリオは次のとおりです。
- すべてのスレッド間で共有されるプロキシがあります。
このプロキシがブロックされた場合、すべてのスレッドではなく、1 つのスレッドのみが ProxyQueue からプロキシをデキューする必要があります。デキューには、現在インターロックを使用しているため、一度に1つのスレッドしか関数に入ることができません。
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); } }