我正在尝试从.csv
文件中读取IP地址,并使用PingAsync类对这些地址进行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();
}
如果我有任何错误,请指导我。
答案 0 :(得分:0)
这段代码就是问题所在:
var pingTasks = ipaddress.Select(ip =>
{
using (var ping = new Ping())
{
return ping.SendPingAsync(ip);
}
}).ToList();
您在Ping
操作有可能完成之前处置async
课程,因为您不等待SendPingAsync
,而只是返回热门它产生的任务。这导致在操作完成之前处置。
将您的代码更改为:
var pingTasks = ipaddress.Select(ip =>
{
var ping = new Ping();
return ping.SendPingAsync(ip);
}).ToList();