我有5个不同的IP,需要与不同的Web请求绑定。
请参阅下面的示例代码。call1()工作得很好。但是,当我尝试使用列表<任务>在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 log2012-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
这是一个非常普遍的混乱,当您处理lambda表达式时,foreach循环中的可变封闭。从本质上讲,如果将Call2()代码更改为下方,则应按预期工作。如果您对为什么会发生这种情况感兴趣,请查看Eric Lippert的博客文章,以获取出色的解释。
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());
}