将不同的IP绑定到每个WebRequest不起作用

时间:2012-10-24 02:20:52

标签: c# httpwebrequest webrequest

我有5个不同的IP需要与不同的Web请求绑定。

请参阅下面的示例代码。 Call1()完美运行。但是当我尝试使用List<任务>在Call2()中,它将错误的IP绑定到请求(我仔细检查请求站点的IIS日志中的IP)。

请帮助!!!

    class Program
    {

        private static string[] IPs = new string[] { "xxx.xxx.xx.xxx", "xxx.xxx.xx.xxx", "xxx.xxx.xx.xxx", "xxx.xxx.xx.xxx", "xxx.xxx.xx.xxx" };
        private static string Url = "http://myfakedomain.com/{0}.aspx";

        static void Main(string[] args)
        {
            Call1();
            Call2();
        }

        static void Call1()
        {
            WebHandler web = new WebHandler();

                foreach (var ip in IPs)
                {
                    web.MakeWebRequest(String.Format(Url,ip), ip);
                }
        }

        static void Call2()
        {
            WebHandler web = new WebHandler();
            List<Task> tasks = new List<Task>();

                foreach (var ip in IPs)
                {
                   var ipCopy = ip;
                    tasks.Add(Task<bool>.Factory.StartNew(() => web.MakeWebRequest(String.Format(Url, ipCopy ), ipCopy )));
                }

                Task.WaitAll(tasks.ToArray());
        }

    }

    public class WebHandler
    {
        public bool MakeWebRequest(string Url, string IP)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.ServicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) => new IPEndPoint(IPAddress.Parse(IP), 0);

            request.KeepAlive = false;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
                {
                    string html = reader.ReadToEnd();
                }
            }

            return true;
        }
    }

以下是Call2()

的IIS日志
2012-10-23 01:53:20 xxx.xxx.xx.xxx GET /xxx.xxx.xx.244.aspx - 80 - xxx.xxx.xx.242 - 200 0 0 1185
2012-10-23 01:53:20 xxx.xxx.xx.xxx GET /xxx.xxx.xx.241.aspx - 80 - xxx.xxx.xx.242 - 200 0 0 1201
2012-10-23 01:53:21 xxx.xxx.xx.xxx GET /xxx.xxx.xx.243.aspx - 80 - xxx.xxx.xx.242 - 200 0 0 608
2012-10-23 01:53:21 xxx.xxx.xx.xxx GET /xxx.xxx.xx.242.aspx - 80 - xxx.xxx.xx.242 - 200 0 0 624
2012-10-23 01:53:21 xxx.xxx.xx.xxx GET /xxx.xxx.xx.245.aspx - 80 - xxx.xxx.xx.242 - 200 0 0 218

1 个答案:

答案 0 :(得分:0)

当你处理lambda表达式时,这是对foreach循环中变量闭包的一个非常常见的混淆。基本上如果你将Call2()代码更改为低于它,它应该按预期工作。如果您对它究竟发生的原因感兴趣,请查看Eric Lippert's blog post以获得出色的解释。

static void Call2()
{
    WebHandler web = new WebHandler();
    List<Task> tasks = new List<Task>();

    foreach (var ip in IPs)
    {
        var ipCopy = ip;
        tasks.Add(Task<bool>.Factory.StartNew(() => web.MakeWebRequest(String.Format(Url, ipCopy), ipCopy)));
    }

    Task.WaitAll(tasks.ToArray());
}