MultiThreaded Proxy Checker

2019-07-21 07:48发布

I have little code like:

            using (WebClient wc = new WebClient())
            {
                wc.Proxy = new WebProxy("IP", Port);

            resume:
                if (!wc.IsBusy)
                {
                    string rtn_msg = string.Empty;
                    try
                    {
                        rtn_msg = wc.DownloadString(new Uri("http://google.com/"));
                    }
                    catch (WebException) { }
                    catch (Exception) { }
                }
                else
                {
                    System.Threading.Thread.Sleep(1000);
                    goto resume;
                }
            }

I am trying to use it with ThreadPool:

        foreach (Proxy proxy in s)
        {
            ThreadPool.QueueUserWorkItem((c) =>
            {
                this.CheckProxy(proxy);
            });
        }

The problem is that the last proxy in the list is checked by all threads.

For example, with ip1, ip2, ip3, ip4 in the proxy list, all the threads check ip4, the last item in list.

Why is that? Any suggestions on how I can get this to work?

1条回答
▲ chillily
2楼-- · 2019-07-21 08:35

If you had a tool like ReSharper it would have warned you with Access to modified closure. You need to make a local copy:

    foreach (Proxy proxy in s)
    {
        var p = proxy;
        ThreadPool.QueueUserWorkItem((c) =>
        {
            this.CheckProxy(p);
        });
    }

Also I would suggest to change your goto into a while loop. Goto is considered bad practice and in your case you do not gain anything from it.

查看更多
登录 后发表回答