使用ping大约200个地址的Windows服务时遇到问题

时间:2015-03-18 19:23:39

标签: c# .net multithreading windows-services

更新了Ping异步问题:Large amount of pings in async task - getting Exception "An asynchronous call is already in progress."

我有一个Windows服务,它从MySQL数据库中获取主机列表,并报告主机是否可以ping通。这适用于少量的IP,但我一次预计会有大约200多个IP,而一两个主机正在关闭会导致很多延迟。我的快速和肮脏的解决方案是在一个线程中打开ping,这样如果一个主机关闭或网络速度慢,循环可以继续运行......它可以工作..但不是很好。我是新手,但我知道这不足以说明这不是最好的方法。任何帮助/指导将不胜感激!

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);
        }
    }

除了占用大量内存之外,一些信息在线程之间被遗漏/重复,这使得它非常不可靠。

0 个答案:

没有答案