Home > Net >  Ping with multithreading
Ping with multithreading

Time:02-11

I did this:

WebClient client = new WebClient();
string[] dns = client.DownloadString("https://public-dns.info/nameservers.txt")
    .Split('\n');
List<string> parsedDns = new List<string>();
foreach (string dnsStr in dns)
{
    Ping ping = new Ping();
    if (dnsStr.Contains(":"))
    {

    }
    else if (ping.SendPingAsync(dnsStr, 150).Result.RoundtripTime <= 150)
    {
        parsedDns.Add(dnsStr);
    }
}

foreach (var dns_ in parsedDns.ToArray())
{
   Console.WriteLine(dns_);
}
Console.ReadKey();

That what it does is collect the DNS of a page, put them in a string[] and then ping them one by one and those with less than 150ms of response are saved and printed on the console. I tried to do it with multithreads but it kept giving me errors and I would like to know how it would be to do this with for example 500 threads without any bugs in order to increase the speed of this process.

CodePudding user response:

You could use the Parallel.ForEachAsync API, that was introduced in .NET 6.

var parsedDns = new ConcurrentQueue<string>();
var options = new ParallelOptions() { MaxDegreeOfParallelism = 10 };

Parallel.ForEachAsync(dns, options, async (dnsStr, ct) =>
{
    Ping ping = new();
    PingReply reply = await ping.SendPingAsync(dnsStr, 150);
    if (reply.RoundtripTime <= 150)
    {
        parsedDns.Enqueue(dnsStr);
    }
}).Wait();

The Parallel.ForEachAsync method returns a Task that you can either await, or simply Wait as in the above example.

  • Related