我找到了一个代码来检查从列表中读取地址并以异步方式对它们进行 ping 并处理结果的多个主机的连接性。
当我使用预定义列表时,例如:
public static List<string> addresses = new List<string> { "172.20.74.1", "192.168.1.103", "192.168.1.104", "192.168.1.105"};
一切正常,但是当我从数据库中读取此列表时,会发生 NullReferenceException。有人可以帮我解决这个问题吗?
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using System.Collections.Generic;
using System;
namespace asyncPing
{
class Program
{
public static List<string> addresses = getNetAddress();
//public static List<string> addresses = new List<string> { "172.20.74.1", "192.168.1.103", "192.168.1.104", "192.168.1.105"};
static void Main(string[] args)
{
List<Task<PingReply>> pingTasks = new List<Task<PingReply>>();
foreach (var address in addresses)
{
Console.WriteLine(address);
}
foreach (var address in addresses)
{
pingTasks.Add(PingAsync(address));
}
//Wait for all the tasks to complete
Task.WaitAll(pingTasks.ToArray());
//Now you can iterate over your list of pingTasks
foreach (var pingTask in pingTasks)
{
Console.WriteLine(pingTask.Result.Address + "\t" + pingTask.Result.Status);
if (pingTask.Result.Status != IPStatus.Success)
{
//Do Some Thing
}
}
Console.ReadLine();
}
public static List<string> getNetAddress()
{
List<string> addr = new List<string>();
string connetionString = @"Data Source=localhost;Initial Catalog=AlarmsDB;Persist Security Info=True;User ID=sa;Password=123456";
using (SqlConnection myConnection = new SqlConnection(connetionString))
{
//Console.WriteLine("Connection Open !");
string oString = "Select ip_address from Networks";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
addr.Add(oReader["ip_address"].ToString());
}
myConnection.Close();
}
}
return addr;
}
static Task<PingReply> PingAsync(string address)
{
var tcs = new TaskCompletionSource<PingReply>();
Ping ping = new Ping();
ping.PingCompleted += (obj, sender) =>
{
tcs.SetResult(sender.Reply);
};
ping.SendAsync(address, new object());
return tcs.Task;
}
}
}
异常发生在行中:
Console.WriteLine(pingTask.Result.Address + "\t" + pingTask.Result.Status);
似乎异步 pings 方法的结果似乎为空。我不知道为什么当从数据库传递相同的输入时,输出的结果会发生变化?