I need to constantly ping about 400 machines, and with this, in order for another functionality of the program to work. I write this:

Task<IPStatus> tstTask(Apteka apt) { return Task.Run(() => { return apt.ping(); }); } async void tstDispRes(DataGridView dvg, List<Apteka> list) { for (int i = 0; i < list.Count; i++) { dvg[4, list[i].numPrint].Value = await tstTask(list[i]); } } 

and after the timer I call

  t2.Start(); t2.Interval = 1000; t2.Tick += (o, v) => { tstDispRes(dataGridView2, arrayOfApteka); }; 

Asynchronous, everything is fine, but how can I make this business multithreaded? I read that when creating a Task, it is entered into the thread pool and executed as if in a separate one, but for some reason this is not noticeable. Direct what to read. Thanks in advance.

1 answer 1

What would I advise you.

Let's write in what form we need to get ping, for example

 public class PingResult { public long RoundtripTime {get;private set;} public IPStatus Status {get;private set;} public PingResult(long roundtripTime, IPStatus status) { this.RoundtripTime = roundtripTime; this.Status = status; } } 

Next, let's say the method for ping

 static async Task<PingResult> Ping(string host, int timeout = 2000) { var ping = new Ping(); var result = await ping.SendPingAsync(host, timeout); return new PingResult(result.RoundtripTime, result.Status); } 

Note that the Ping method is asynchronous. That is, when I call it - no matter how many threads I use, the wait will still be asynchronous. That is, until I wait for the results of the ping, the processor will not be busy at all.

It’s pretty simple to call such code.

 var hosts = Enumerable.Repeat("www.google.com", 100).ToArray(); var tasks = hosts.Select(x=>Ping(x)).ToArray(); var results = await Task.WhenAll(tasks); foreach (var result in results) Console.WriteLine($"{result.Status} - {result.RoundtripTime}"); 

What is happening here: first I create a collection of 100 hosts. Then I run 100 tasks to poll the hosts. I note that these tasks are not executed in the thread pool, since these tasks work with the network, what they expect (response via network) does not concern the processor at all. Further, I asynchronously expect when all created tasks are completed - this waiting also does not take up the processor. And, at the end, I list the results.

  • thank you very much) - Vitaliy Shebanits