public static string pingAllChildren(string myIp) { object locker = new object(); string res = string.Empty; for (int i = 1; i < 5; i++) { int j = i; Task.Run(async () => { string ip = myIp.Remove(myIp.LastIndexOf('.'), myIp.Length - myIp.LastIndexOf('.')) + $".{j + 10}"; IPStatus t = await pingAsync($"{ip}"); lock (locker) { res += $"{ip} : {t.ToString()}\n"; } }).Wait(); //string ip = myIp.Remove(myIp.LastIndexOf('.'), myIp.Length - myIp.LastIndexOf('.')) + $".{j + 10}"; //ThreadPool.QueueUserWorkItem(pingAsync(ip)); } return res; } if Wait() removed, then return an empty result. And so no asynchrony.
How do I wait for all threads to complete to return the result normally?
Task.Run. ThepingAsyncmethod returns a task, here these tasks and put in an array (sheet). Then wait for them to completeTask.Wait. As a result, all pings are performed in parallel. This does not create a single excess flow. It does not need a lock: discardlock. - Alexander Petrov