MultiThreaded Proxy Checker

可紊 提交于 2019-12-24 01:07:57

问题


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:


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.



来源:https://stackoverflow.com/questions/6235651/multithreaded-proxy-checker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!