以下のコードでWaitAllに問題があります。このメソッドはIPアドレスとポート(WMIポート135をスキャンしています)のリストを受け取り、ポートが開いているIPアドレスのリストを返します。私はこのコードを遅くすると、実行して正しいシステムを返すようにWaitAllが正しく実装されていないと信じています。ありがとう。開いているTCPポートをスキャンするためのスレッド処理
private static List<IPAddress> openSystems = new List<IPAddress>();
public static List<IPAddress> Scan(List<IPAddress> addresses, ushort port)
{
int count = addresses.Count;
Task[] tasks = new Task[count];
//Loop through ip address
for(int x = 0; x <= count -1; x++)
{
tasks[x] = Task.Factory.StartNew(() =>
{
using (TcpClient tcp = new TcpClient())
{
try
{
Console.WriteLine("Trying to get into {0}", addresses[x]);
tcp.Connect(addresses[x], port);
openSystems.Add(addresses[x]);
}
catch
{
Console.WriteLine("Can't get into {0}", addresses[x]);
//ignore exceptions
}
}
});
}
Task.WaitAll(tasks);
return openSystems;
}
問題は何ですか?そして、どのように「コードを遅くする」のですか?また、 'openSystems.Add(addresses [x])'の周りに 'lock'が必要です。[' concurrent collections'](https://msdn.microsoft.com/en-us/library/system) .collections.concurrent(v = vs.110).aspx) – Quantic
例外を無視しないでください_常に_悪い考えですか? –