在委托声明中引用 i 是否有效?
targets[i].PingReply = e.Reply;
它会引用定义在
pingSender.SendAsync( targets[i].IPAddress, targets[i].Timeout);
还是当委托触发时 i 的值会有所不同?我问是因为我在 PingCompleted 中获得了 i=3 的索引超出范围,我不知道为什么。
public void Ping(PingTest[] targets)
{
var finished = new CountdownEvent(targets.Count());
for (int i = 0; i < targets.Count(); i++)
{
finished.AddCount();
var pingSender = new Ping();
pingSender.PingCompleted += (sender, e) =>
{
targets[i].PingReply = e.Reply;
finished.Signal();
};
pingSender.SendAsync(targets[i].IPAddress, targets[i].Timeout);
}
finished.Signal();
finished.Wait();
}
这是电话...
var pingTests = new PingTest[]
{
new PingTest("Router", new IPAddress(new byte[] {192, 168, 1, 8}), 2),
new PingTest("Exchange", new IPAddress(new byte[] {192, 168, 1, 78}), 3),
new PingTest("SQL", new IPAddress(new byte[] {192, 168, 1, 99}), 3)
};
netwrkService.Ping(pingTests);