0

So I have this code that I have written which checks all proxies in my ConcurrentQueue list, but I was wondering what if I just wanted to check if 1 proxy worked and then exit out of it? So I tried adding Boolean operators to test whether the proxyworking list had more than 1 proxy in it, but yet it still continued to check all the proxies.

System.Threading.Tasks.Parallel.ForEach(proxies, Sub(proxy)
        Dim myProxy = New WebProxy(proxy)
        Dim r As HttpWebRequest = HttpWebRequest.Create("http://www.google.com")
        r.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36"
        r.Timeout = 3000
        r.Proxy = myProxy
        Try
            Using re As HttpWebResponse = r.GetResponse()
                Console.WriteLine("Proxy Working: " & proxy & vbNewLine)
                SyncLock workingProxies
                    workingProxies.Add(proxy)
                End SyncLock
            End Using
        Catch ex As Exception
            Console.WriteLine(ex.Message & " Proxy Not Working! " & proxy & vbNewLine)
        End Try
    End Sub)

That's the code I'm working with at the moment and when it runs the line workingProxies.Add(proxy) I want the tasks to stop and run a function.

Blackwood
  • 4,504
  • 16
  • 32
  • 41
1ben99
  • 557
  • 1
  • 7
  • 14
  • Read the documentation for the `Parallel.ForEach` method and pay attention to the overloads that utilise the `ParallelLoopState` class. Based on what I've read, the `Stop` method of that class is of interest to you: "Stop is typically employed in search-based algorithms, where once a result is found, no other iterations need be executed". – jmcilhinney Aug 23 '17 at 02:23
  • Thanks for that advice - I have since added a state.stop() and return onto the end of testing the proxy. However, a few tasks still occur even after I tell them to stop. Now obviously this is because the tasks have already initialized before the stop request has come in, so is there a way to stop current tasks too? – 1ben99 Aug 23 '17 at 04:00

0 Answers0