Вы можете использовать UserState
свойство и блокировку для обеспечения сериализованного доступа к GameList
:
byte[] buffer = Encoding.ASCII.GetBytes (new string('a', 32));
var options = new PingOptions (32, true);
Ping p = new Ping();
p.PingCompleted += p_PingCompleted;
foreach (Game curgame in GameList.ToArray())
{
// e.UserState will be curgame
p.SendAsync(IPAddress.Parse(curgame.IP), 2500, buffer, options, curgame);
}
Тогда в вашем p_PingCompleted
обработчике:
void p_PingCompleted(object sender, PingCompletedEventArgs e)
{
var game = (Game)e.UserState;
if (e.Reply.Status != IPStatus.Success)
{
Console.WriteLine(
" Could not reach {0} ({1}), removing this server...",
game.IP,
e.Reply.Status);
lock (GameList)
{
GameList.Remove(game);
}
}
else
{
Console.WriteLine(
"Ping reply from: {0} in {1} ms",
e.Reply.Address,
e.Reply.RoundtripTime);
if (e.Reply.RoundtripTime == 0 ||
e.Reply.RoundtripTime >= 2500)
{
Console.WriteLine(" Ping too high, removing this server...");
lock (GameList)
{
GameList.Remove(game);
}
}
}
}