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?

    1 answer 1

    Try using Parallel.ForEach

    For example:

     List<string> ips = await PingSuccess(); ParallelOptions opts = new ParallelOptions(); opt.MaxDegreeOfParallelism = 10; Parallel.ForEach<string>(ips, opts, x => { var osVer = OSVersion(x); Console.WriteLine($"IP: {x} => OS: {osVer}"); }); 
    • MaxDegreeOfParallelism from the MaxDegreeOfParallelism not necessary. It is better to try several values: ..., X / 2, X (the default value), X * 2, ..., where X is the number of processors. - andreycha
    • @andreycha. For good, you need MaxDegreeOfParallelism should be equal to the number of processor threads, because "extra" threads will be idle, waiting for their turn. But there shouldn't be any serious problems at relatively low MaxDegreeOfParallelism values - Chloroform