I study multithreading and for example I make a program that collects data from a local network.
First, I collect a list of ping hosts on the network.
public async static Task<List<string>> PingSuccess() { int i = 1; List<string> ips = new List<string>(); List<string> ips_complite = new List<string>(); while (i <= 255) { ips.Add(ip_base + i); i++; } var pingTargetHosts = ips; var pingTasks = pingTargetHosts.Select(host => new Ping().SendPingAsync(host, 2000)).ToList(); var pingResults = await Task.WhenAll(pingTasks); foreach (var ping in pingResults) { if (ping.Status == IPStatus.Success) { ips_complite.Add(ping.Address.ToString()); } } return ips_complite; } Then I need to understand under which operating system all these hosts work.
I have to take the List from the method above and use foreach to go through it to the end. In normal mode, this happens for a very long time, because I am accessing via WMI, consistently to each computer and waiting for a response from it.
public static object OSVersion(object ip) { string result = string.Empty; try { ManagementScope scope = new ManagementScope("\\\\" + (string)ip + "\\root\\cimv2"); scope.Connect(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); foreach (ManagementObject os in searcher.Get()) { result = os["Caption"].ToString(); return result; } } catch { } return result; } How to sort out the list for me correctly and with the help of what, so that I create for example 10 threads that will send a request and, when an answer appears, will immediately be output to the console?