发生 PingException mscorlib.dll

PingException occurred mscorlib.dll

我正在尝试从 .csv 文件读取 IP 地址并使用 PingAsync class ping 这些地址。但是我在下面的行中遇到了异常。

await Task.WhenAll(pingTasks);

我的完整代码如下,请看一下。

Ping 方法

private static async Task AsyncPingTask(List<string> ipaddress)
{
    try
    {
        Console.WriteLine("Ping Started");
        StringBuilder pingStringBuilder = new StringBuilder();


            var pingTasks = ipaddress.Select(ip =>
            {
                using (var ping = new Ping())
                {
                    return ping.SendPingAsync(ip);
                }
            }).ToList();

            Console.WriteLine("Ping Completed");

            await Task.WhenAll(pingTasks);


            foreach (var pingReply in pingTasks)
            {
                pingStringBuilder.Append(pingReply.Result.Address);
                pingStringBuilder.Append("-->");
                pingStringBuilder.Append(pingReply.Result.Status);
                pingStringBuilder.Append("-->");
                pingStringBuilder.Append(pingReply.Result.RoundtripTime.ToString());
                pingStringBuilder.AppendLine();
            }
            Console.WriteLine(pingStringBuilder.ToString());
            pingStringBuilder.Clear();                

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
        throw;
    }

    }

主要方法:

public static void Main()
{
    List<string> address = new List<string>();
    Task t = Task.Run(() =>
    {
        var reader = new StreamReader(File.OpenRead(Environment.CurrentDirectory+@"\address.csv"));
        while (!reader.EndOfStream)
        {
            var lines = reader.ReadLine();
            var values = lines.Split(';');
            address.Add(values[0]);
        }                
    });


    Console.WriteLine("List COunt is {0}",address.Count);
    Stopwatch timeSpan=Stopwatch.StartNew();


    t.Wait();            


    AsyncPingTask(address).Wait();

    Console.WriteLine(timeSpan.ElapsedMilliseconds);                        
    Console.ReadLine();
}

如果我有任何错误,请指导我。

这段代码有问题:

var pingTasks = ipaddress.Select(ip =>
{
    using (var ping = new Ping())
    {
        return ping.SendPingAsync(ip);
    }
}).ToList();

您在 async 操作有机会完成之前处理 Ping class,因为您不是在等待 SendPingAsync,而是简单地返回它产生的热门任务。这导致在操作完成之前进行处理。

将您的代码更改为:

var pingTasks = ipaddress.Select(ip =>
{
    var ping = new Ping();
    return ping.SendPingAsync(ip);
}).ToList();