服务器监控工具中的多线程

时间:2014-03-13 13:00:42

标签: multithreading

我创建了一个服务器监控工具。现在应用程序的性能非常慢。显示18台服务器的服务器状态需要6分钟,但我需要让应用程序更快..任何人都可以帮我多线程下面提到的代码。代码中没有错误。它工作正常,但我需要让它更快..

以下是代码: -

namespace AutoReport
{
public partial class Form1 : Form
{
    DataTable dt;

    string accessconn = ConfigurationManager.ConnectionStrings["accessconn"].ConnectionString;
    Form2 frm2 = new Form2();
    //public string MyValueapp
    //{
    //    get { return app.Text; }
    //}
    //public string MyValueip
    //{
    //    get { return ip.Text; }
    //}  

    public Form1()
    {

        InitializeComponent();

        //app.Text = frm2.MyValueapp;
        //ip.Text = frm2.MyValueip;

    }

    //public Form1(string appName, string ipAddress)
    //{
    //    InitializeComponent();
    //    app.Text = appName;
    //    ip.Text = ipAddress;
    //}



    public void IsConnectedToInternet()
    {
    }


    private void btnExit_Click_Click(object sender, EventArgs e)           //This indicates the Exit method.
    {
        Application.Exit();
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        //pictureBox1.Cursor = Cursors.Hand;
        //this.Cursor = Cursors.Hand;
        //Cursor.Current = Cursors.Hand;
        Process proc = new Process();
        proc.EnableRaisingEvents = false;
        proc.StartInfo.FileName = "iexplore.exe";
        proc.StartInfo.Arguments = "http://www.jpmorganchase.com/corporate/Home/home.htm";
        proc.Start();
        proc.Close();
        proc.Dispose();
    }
    private Timer timer1;
    public void InitTimer()
    {
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 900 * 1000; // in miliseconds
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        timer1.Stop();
        Cursor.Current = Cursors.WaitCursor;
        //dt.Rows.Add(AppName.Text.ToString().Trim(), server_IP.Text.ToString().Trim(), getServerStatus(server_IP.Text.ToString().Trim()), getMachineName(server_IP.Text.ToString().Trim()), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        Form1_Load(null, null);
        bindDataTableToGrid();
        Cursor.Current = Cursors.Default;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        InitTimer();

        //String Name=AppName.Text.ToString().Trim();
        dt = new DataTable();
        DataColumn App_Name = new DataColumn("Application Name");
        DataColumn ServerIP = new DataColumn("Server IP");
        DataColumn serverStatus = new DataColumn("Server Status");
        DataColumn pcName = new DataColumn("PC Name");
        DataColumn Date = new DataColumn("Date");
        DataColumn Time = new DataColumn("Time");
        DataColumn TimeZone = new DataColumn("Local Time Zone");
        String time = System.DateTime.UtcNow.ToString();

        dt.Columns.Add(App_Name);
        dt.Columns.Add(ServerIP);
        dt.Columns.Add(serverStatus);
        dt.Columns.Add(pcName);
        dt.Columns.Add(Date);
        dt.Columns.Add(Time);
        dt.Columns.Add(TimeZone);
        dt.Columns[0].AllowDBNull = true;
        dt.Columns[1].AllowDBNull = true;
        //dt.Columns[2].AllowDBNull = false;
        //dt.Columns[3].AllowDBNull = false;

        dt.Rows.Add("CAS", "172.16.4.24", getServerStatus("172.16.4.24"), getMachineName("172.16.4.24"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("JPMC", "172.30.130.56", getServerStatus("172.30.130.56"), getMachineName("172.30.130.56"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("Filenet", "172.30.130.84", getServerStatus("172.30.130.84"), getMachineName("172.30.130.84"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("CAMOVEIT", "172.30.130.85", getServerStatus("172.30.130.85"), getMachineName("172.30.130.85"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);

        dt.Rows.Add("CAS", "172.30.132.45", getServerStatus("172.30.132.45"), getMachineName("172.30.132.45"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("Filenet", "172.30.132.53", getServerStatus("172.30.132.53"), getMachineName("172.30.132.53"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("Filenet", "172.30.144.65", getServerStatus("172.30.144.65"), getMachineName("172.30.144.65"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("CAMOVEIT", "192.168.133.21", getServerStatus("192.168.133.21"), getMachineName("192.168.133.21"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("CAS", "172.30.130.81", getServerStatus("172.30.130.81"), getMachineName("172.30.130.81"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("Filenet", "172.30.139.205", getServerStatus("172.30.139.205"), getMachineName("172.30.139.205"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("CAMOVEIT", "172.30.130.75", getServerStatus("172.30.130.75"), getMachineName("172.30.130.75"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("CAS", "172.26.50.67", getServerStatus("172.26.50.67"), getMachineName("172.26.50.67"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("WebDe", "172.30.130.82", getServerStatus("172.30.130.82"), getMachineName("172.30.130.82"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("WebDe", "172.30.157.67", getServerStatus("172.30.157.67"), getMachineName("172.30.157.67"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("WebDe", "10.233.84.70", getServerStatus("10.233.84.70"), getMachineName("10.233.84.70"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        dt.Rows.Add("WebDe", "10.233.82.11", getServerStatus("10.233.82.11"), getMachineName("10.233.82.11"), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);

        IP_Status_Grid.DataSource = dt;

        /* foreach (DataGridViewRow row in IP_Status_Grid.Rows)
         {
             Ping p = new Ping();

             PingReply reply = p.Send(row.Cells[1].Value.ToString());
             if (reply.Status == IPStatus.Success)
                 row.Cells[2].Value = "Server is ON";

             else
                 row.Cells[2].Value = "Server is OFF";

         }*/



        string machineName = string.Empty;
        /* foreach (DataGridViewRow pc in IP_Status_Grid.Rows)
         {
             ProcessStartInfo info = new ProcessStartInfo();
             info.Arguments = "/C ping -a " + pc.Cells[1].Value.ToString();
             info.WindowStyle = ProcessWindowStyle.Hidden;
             info.CreateNoWindow = true;
             info.FileName = "cmd.exe";
             info.UseShellExecute = false;
             info.RedirectStandardOutput = true;
             using (Process process = Process.Start(info))
             {
                 using (StreamReader reader = process.StandardOutput)
                 {
                     string result = reader.ReadToEnd();
                     //pc.Cells[3].Value = result;
                     //var result = Regex.Replace(yourString, "^[^A-Za-z0-9]*", "");
                     pc.Cells[3].Value = Regex.Replace(result.Substring(10, 12), "[^A-Za-z0-9]*", "");
                     if (result.Contains("Request timed out"))
                     {
                         //&& result.Contains("expired")
                         pc.Cells[3].Value = "No Computer found";
                     }
                 }
             }

             //IPHostEntry hostEntry = Dns.GetHostEntry(pc.Cells[1].Value.ToString());
             //machineName = hostEntry.HostName;

         }*/

        //foreach (DataGridViewRow pc in IP_Status_Grid.Rows)
        //{
        //    //pc.Cells[6].Value = TimeZoneInfo.Local.DaylightName;
        //    //pc.Cells[4].Value = System.DateTime.Today;
        //    //String time = System.DateTime.UtcNow.ToString();
        //    //pc.Cells[5].Value = time.Substring(9, 11);
        //    pc.Cells[6].Value = TimeZoneInfo.Local;



        //}
        /*
        this.IP_Status_Grid.DataSource = dt;

        this.IP_Status_Grid.AllowUserToAddRows = false;*/

        bindDataTableToGrid();
        AddARow(dt);

    }

    private void bindDataTableToGrid()
    {
        this.IP_Status_Grid.DataSource = dt;

        this.IP_Status_Grid.AllowUserToAddRows = false;
    }

    private void ServerStatus_Click(object sender, EventArgs e)
    {
        //getHostName();
        //IsConnectedToInternet();
        //DataRow dr1 = dt.NewRow();
        //dr1[0] = textuser.Text;
        //dr1[1] = textsystemip.Text;
        //dt.Rows.Add(dr1);
        //IP_Status_Grid.DataSource = dt;
        //IP_Status_Grid.AutoGenerateColumns=true;
    }

    private void refresh_Click(object sender, EventArgs e)
    {
        Cursor.Current = Cursors.WaitCursor;
        //dt.Rows.Add(AppName.Text.ToString().Trim(), server_IP.Text.ToString().Trim(), getServerStatus(server_IP.Text.ToString().Trim()), getMachineName(server_IP.Text.ToString().Trim()), System.DateTime.Today, gettime(System.DateTime.UtcNow.ToString()), TimeZoneInfo.Local);
        Form1_Load(null, null);
        bindDataTableToGrid();

        Cursor.Current = Cursors.Default;
        MessageBox.Show("Grid Refreshed");


    }

    private void btnExit_Click_Click_1(object sender, EventArgs e)
    {
        Application.Exit();
    }





    private void AddARow(DataTable table)
    {
        // Use the NewRow method to create a DataRow with 
        // the table's schema.
        DataRow newRow = table.NewRow();

        // Add the row to the rows collection.
        table.Rows.Add(newRow);
    }

    //private void button2_Click(object sender, EventArgs e)
    //{
    //    newUser.Visible = false;
    //}

    private void Delete_Click(object sender, EventArgs e)
    {
        Int32 selectedRowCount = IP_Status_Grid.Rows.GetRowCount(DataGridViewElementStates.Selected);
        DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNo);

        if (selectedRowCount > 0)
        {
            if (IP_Status_Grid.Rows.OfType<DataGridViewRow>().Last().Selected == true)
            {
                MessageBox.Show("Last row can not be deleted");

            }
            else
            {
                foreach (DataGridViewRow item in this.IP_Status_Grid.SelectedRows)
                {
                    if (result == DialogResult.Yes)

                        IP_Status_Grid.Rows.RemoveAt(item.Index);
                    //if (result == DialogResult.No)
                    //    e.Cancel = true;


                }
            }
        }
        else
        {
            MessageBox.Show("Please select a row from above Grid, except the last one.");
        }
    }

    private void Search_Click_1(object sender, EventArgs e)
    {
        //Form2 child=new Form2();
        //child.AppName.Text = app.Text;
        //child.server_IP.Text = ip.Text;


        Cursor.Current = Cursors.WaitCursor;
        string valueFromTextBox = server_IP.Text;

        if (Regex.IsMatch(valueFromTextBox, @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"))
        {
            if (AppName.Text == "" || server_IP.Text == "")
            {
                MessageBox.Show("Application_Name or Server_Ip can not be empty");

            }
            else
            {
                IP_Status_Grid[0, IP_Status_Grid.Rows.Count - 1].Value = AppName.Text.Trim();
                IP_Status_Grid[1, IP_Status_Grid.Rows.Count - 1].Value = server_IP.Text.Trim();
                Ping p = new Ping();

                PingReply reply = p.Send(IP_Status_Grid[1, IP_Status_Grid.Rows.Count - 1].Value.ToString());
                if (reply.Status == IPStatus.Success)
                    IP_Status_Grid[2, IP_Status_Grid.Rows.Count - 1].Value = "Server is ON";

                else
                    IP_Status_Grid[2, IP_Status_Grid.Rows.Count - 1].Value = "Server is OFF";



                string machineName = string.Empty;

                ProcessStartInfo info = new ProcessStartInfo();
                info.Arguments = "/C ping -a " + IP_Status_Grid[1, IP_Status_Grid.Rows.Count - 1].Value.ToString();
                info.WindowStyle = ProcessWindowStyle.Hidden;
                info.CreateNoWindow = true;
                info.FileName = "cmd.exe";
                info.UseShellExecute = false;
                info.RedirectStandardOutput = true;
                using (Process process = Process.Start(info))
                {
                    using (StreamReader reader = process.StandardOutput)
                    {
                        string result = reader.ReadToEnd();
                        //pc.Cells[3].Value = result;
                        //var result = Regex.Replace(yourString, "^[^A-Za-z0-9]*", "");
                        IP_Status_Grid[3, IP_Status_Grid.Rows.Count - 1].Value = Regex.Replace(result.Substring(10, 12), "[^A-Za-z0-9]*", "");
                        if (result.Contains("Request timed out"))
                        {
                            //&& result.Contains("expired")
                            IP_Status_Grid[3, IP_Status_Grid.Rows.Count - 1].Value = "No Computer found";
                        }
                    }
                }





                //pc.Cells[6].Value = TimeZoneInfo.Local.DaylightName;
                IP_Status_Grid[4, IP_Status_Grid.Rows.Count - 1].Value = System.DateTime.Today;
                String time = System.DateTime.UtcNow.ToString();
                IP_Status_Grid[5, IP_Status_Grid.Rows.Count - 1].Value = time.Substring(9, 11);
                IP_Status_Grid[6, IP_Status_Grid.Rows.Count - 1].Value = TimeZoneInfo.Local;
                AppName.Text = "";
                server_IP.Text = "";
                AddARow(dt);
                bindDataTableToGrid();

            }

            Cursor.Current = Cursors.Default;
            //newUser.Visible = false;
        }
        else
        {
            MessageBox.Show("Please Enter Only Numbers like as Server IP");
        }
        bindDataTableToGrid();
    }



    private void ToCsV(DataGridView dGV, string filename)
    {
        string stOutput = "";
        // Export titles:
        string sHeaders = "";

        for (int j = 0; j < dGV.Columns.Count; j++)
            sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
        stOutput += sHeaders + "\r\n";
        // Export data.
        for (int i = 0; i < dGV.RowCount - 1; i++)
        {
            string stLine = "";
            for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
                stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
            stOutput += stLine + "\r\n";
        }
        Encoding utf16 = Encoding.GetEncoding(1254);
        byte[] output = utf16.GetBytes(stOutput);
        FileStream fs = new FileStream(filename, FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(output, 0, output.Length); //write the encoded file
        bw.Flush();
        bw.Close();
        fs.Close();
    }

    private void new_User_Click_1(object sender, EventArgs e)
    {

        //Form2 popup = new Form2();
        //DialogResult dialogresult = popup.ShowDialog();
        //if (dialogresult == DialogResult.OK)
        //{
        //    Form2 frm2 = new Form2();
        //    app.Text = frm2.MyValueapp;
        //    ip.Text = frm2.MyValueip;

        //    Search_Click(null, null);
        //    popup.Close();
        //}
        //else if (dialogresult == DialogResult.Cancel)
        //{
        //    popup.Dispose();

        //}
        newUser.Visible = true;

    }

    private void extract_result_Click_1(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Excel Documents (*.xls)|*.xls";
        sfd.FileName = "export.xls";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            //ToCsV(dataGridView1, @"c:\export.xls");
            ToCsV(IP_Status_Grid, sfd.FileName); // Here dataGridview1 is your grid view name 
        }
    }

    private void Exit_Click(object sender, EventArgs e)
    {
        newUser.Visible = false;
    }

    //private void Delete_Click(object sender, EventArgs e)
    //{

    //}



    //private void IP_Status_Grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
    //{

    //}


    public string getServerStatus(string ipAddress)
    {
        Ping p = new Ping();
        string retVal = string.Empty;
        PingReply reply = p.Send(ipAddress);
        if (reply.Status == IPStatus.Success)
            retVal = "Server is ON";

        else
            retVal = "Server is OFF";
        return retVal;
    }
    public string gettime(String time)
    {
        String rtrn = string.Empty;
        //String timeval = System.DateTime.UtcNow.ToString();
        rtrn = time.Substring(9, 11);
        return rtrn;
    }

    public string getMachineName(string ipAddress)
    {
        string retVal = string.Empty;
        ProcessStartInfo info = new ProcessStartInfo();
        info.Arguments = "/C ping -a " + ipAddress;
        info.WindowStyle = ProcessWindowStyle.Hidden;
        info.CreateNoWindow = true;
        info.FileName = "cmd.exe";
        info.UseShellExecute = false;
        info.RedirectStandardOutput = true;
        using (Process process = Process.Start(info))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                retVal = Regex.Replace(result.Substring(10, 12), "[^A-Za-z0-9]*", "");
                if (result.Contains("Request timed out"))
                {
                    //&& result.Contains("expired")
                    retVal = "No Computer found";
                }
            }
        }
        return retVal;
    }

    private void thread_Click(object sender, EventArgs e)
    {
        //new System.Threading.Thread(() =>
        //{
        //    string result = test("AMIT");
        //    Dispatcher.BeginInvoke((Action)(() => lblThread1.Text = result));
        //}).Start();
        //lblThread1.Text = "Working...";

    }
    public string test(string message)
    {
        System.Threading.Thread.Sleep(2000);
        return "Hello" + message;
    }
}
}

0 个答案:

没有答案