C# ping ~200个地址的windows服务出现问题
更新了Ping Async的问题: 我有一个Windows服务,它从MySQL数据库获取主机列表,并报告主机是否可ping。这对少量IP非常有效,但我预计一次大约有200多个IP,一两台主机停机会造成很大的延迟。我的快速而肮脏的解决方案是在一个线程中打开ping,这样当一台主机停机或网络速度较慢时,循环可以继续运行。。。它起作用了。。但不太好。我是新手,但我知道这不是最好的方法。任何帮助/指导都将不胜感激C# ping ~200个地址的windows服务出现问题,c#,.net,multithreading,windows-services,C#,.net,Multithreading,Windows Services,更新了Ping Async的问题: 我有一个Windows服务,它从MySQL数据库获取主机列表,并报告主机是否可ping。这对少量IP非常有效,但我预计一次大约有200多个IP,一两台主机停机会造成很大的延迟。我的快速而肮脏的解决方案是在一个线程中打开ping,这样当一台主机停机或网络速度较慢时,循环可以继续运行。。。它起作用了。。但不太好。我是新手,但我知道这不是最好的方法。任何帮助/指导都将不胜感激 try { MySqlConnection Con
try
{
MySqlConnection Connection = new MySqlConnection(ConnectionString);
Connection.Open();
MySqlCommand query = Connection.CreateCommand();
query.CommandText = "SELECT obj_id AS id,ip FROM objects LIMIT 200";
MySqlDataReader Nodes = query.ExecuteReader();
// Record in log that a NEW iteration is starting - for tracking issues with pings
Library.WriteErrorLog("######################## New Iteration ########################");
int i = 1;
while(Nodes.Read())
{
// Open a new thread for each ping. There are over 2000 host objects in the database - if we do not open in seperate threads we will never finish
// each thread will ping the hosts and results will be logged in log.txt and MySQL
string Host = (i == 5 ? "google.com" : Nodes["ip"].ToString());
Host = (i == 4 ? "lindevenv" : Host);
int HostID = int.Parse(Nodes["id"].ToString()); // Obj -> string -> int because super awesome .NET logic
Thread thread = new Thread(() => UpdateStatus(Host, HostID, ConnectionString, i));
thread.Start();
i++;
}
Connection.Close();
}
catch(Exception ee)
{
Library.WriteErrorLog("Error: " + ee.ToString());
}
而且
// Called by the thread as the worker method inside CheckStatus Method below
private void UpdateStatus(string Host, int HostID, string ConnectionString, int loopID)
{
try
{
Ping pinger = new Ping();
PingReply reply = pinger.Send(Host, 3000);
if (reply.Status == IPStatus.Success)
{
Library.WriteErrorLog("(" + loopID + ") " + Host + " is UP!");
}
else
{
Library.WriteErrorLog("(" + loopID + ") " + Host + " is DOWN!");
Library.ReportDown(HostID, ConnectionString);
}
}
catch (PingException e)
{
// Do not throw exception - a pingexception is thrown when there is a timeout/dns/other issue - report as down
Library.WriteErrorLog("(" + loopID + ") " + Host + " is DOWN!");
Library.ReportDown(HostID, ConnectionString);
}
}
除了占用大量内存之外,一些信息在线程之间被遗漏/复制,这使得它非常不可靠。听起来您需要使用Ping.SendAsync而不是Ping.Send。@HarryJohnston我在实现Ping.SendAsync时遇到问题-这里发布了一个问题