C#程序变得反应迟钝 [英] C# program becomes unresponsive

查看:130
本文介绍了C#程序变得反应迟钝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络监控程序,它持续监控网络上的IP地址列表,并将日志写入日志文件。该程序可以正常工作,但在连续运行几天后,UI挂断,任务管理器开始显示我的进程占用过多的CPU,这是非常不自然的。任何有助于改善它的帮助都将非常受欢迎。



提前致谢。



P.S. - 我包含了快速审查的代码。



MainForm.cs

I have a network monitor program which continually monitors a list of ip addresses on the network and writes the log to a log file. The program works all right but after a few days of continuous running the UI hangs up and the task manager starts showing that my process is making too much CPU usage, which is quite unnatural. Any help to make it better will be very welcome.

Thanks in advance.

P.S. - I am including the code for a quick review.

MainForm.cs

using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Threading;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Windows.Forms;

namespace NetworkMonitor
{
    public partial class MainForm : Form
    {
        private List<NetworkLocation> LocationList;
        private delegate void nlss(NetworkLocation nl);
        private Thread PingSender;
        private LogWriter writer;

        public MainForm()
        {
            InitializeComponent();
            LocationList=new List<NetworkLocation>();
            PingSender = new Thread(this.CheckIpAsync);
            writer = new LogWriter();
        }

        public bool AddNetworkLocation(string name,string address)
        {
            NetworkLocation temp;

            if (name.Length == 0)
            {
                MessageBox.Show("Enter a name","Network Monitor",MessageBoxButtons.OK);
                return false;
            }
            else if (!ValidIp(address))
            {
                MessageBox.Show("Enter a valid ip/hostname", "Network Monitor", MessageBoxButtons.OK);
                return false;
            }

            temp=new NetworkLocation(name,address);
            LocationList.Add(temp);
            return true;
        }

        private bool ValidIp(string address)
        {
            string[] parts = address.Split(new char[] { '.' }, StringSplitOptions.None);

            if (parts.Length != 4)
                return false;
            else if ( parts[0].Length == 0 || parts[1].Length == 0 || parts[2].Length == 0 || parts[3].Length == 0)
                return false;
            else
            {
                try
                {
                    int a, b, c, d;

                    a = int.Parse(parts[0]);
                    b = int.Parse(parts[1]);
                    c = int.Parse(parts[2]);
                    d = int.Parse(parts[3]);

                    if ((a < 0 || a > 255) || (b < 0 || b > 255) || (c < 0 || c > 255) || (d < 0 || d > 255))
                        return false;
                    else
                        return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        public void CheckIpAsync()
        {
            try
            {       
                while (true)
                {
                    NetworkLocation[] all_locations = new NetworkLocation[LocationList.Count];

                    LocationList.CopyTo(all_locations);
                    foreach (NetworkLocation nl in all_locations)
                    {
                        this.BeginInvoke(new nlss(this.NetworkLocationSetStatus), new Object[] { nl });
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception)
            {
                writer.WriteLine("IP checking stopped at " + DateTime.Now);
                writer.WriteLine("-------------------------------------------------------------------");
                writer.Stop();
            }            
        }

        public void NetworkLocationSetStatus(NetworkLocation nl)
        {            
            try
            {
                Ping ipchecker = new Ping();
                PingReply reply = ipchecker.Send(nl.Address, 1000);

                if (reply.Status == IPStatus.Success && nl.IsAlive == false)
                {
                    writer.WriteLine(nl.Name + "[" + nl.Address + "] went alive at " + DateTime.Now);
                    nl.IsAlive = true;
                }
                else if (reply.Status != IPStatus.Success && nl.IsAlive == true)
                {
                    writer.WriteLine(nl.Name + "[" + nl.Address + "] went dead at " + DateTime.Now);
                    nl.IsAlive = false;
                }
            }
            catch (Exception)
            {
                writer.WriteLine(nl.Name + "[" + nl.Address + "] went dead at " + DateTime.Now);
            }
        }

        private void AddLocationButton_Click(object sender, EventArgs e)
        {
            AddLocation f = new AddLocation(this);
            f.ShowDialog();
        }

        private void AboutButton_Click(object sender, EventArgs e)
        {
            NetworkMonitorAboutBox f = new NetworkMonitorAboutBox();
            f.ShowDialog();
        }

        private void Watchmantimer_Tick(object sender, EventArgs e)
        {
            int index = -1;

            try
            {
                index = LocationListView.SelectedIndices[0];
            }
            catch (Exception)
            {
            }
            finally
            {
                LocationListView.Items.Clear();

                foreach (NetworkLocation l in LocationList)
                {
                    ListViewItem li = LocationListView.Items.Add(l.Name);
                    li.SubItems.Add(l.Address);
                    li.ImageIndex = l.IsAlive ? 0 : 1;
                }

                if (index >= LocationListView.Items.Count)
                    index = -1;

                if (index != -1)
                    LocationListView.Items[index].Selected = true;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult rs = MessageBox.Show("Click Yes to close application \nClick No to minimize\n& Click Cancel to close this dialog", "Network Monitor", MessageBoxButtons.YesNoCancel);

            if (rs == DialogResult.Yes)
            {
                if (PingSender.IsAlive)
                {
                    PingSender.Abort();
                }

                try
                {
                    File.Delete("NetworkMonitor.xml");

                    XmlTextWriter xmlWriter = new XmlTextWriter("NetworkMonitor.xml", System.Text.Encoding.UTF8);
                    //creating XmlTestWriter, and passing file name and encoding type as argument
                    xmlWriter.Formatting = Formatting.Indented;
                    //setting XmlWriter formating to be indented
                    xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                    //writing version and encoding type of XML in file.
                    xmlWriter.WriteStartElement("NetworkLocationList");
                    //writing first element
                    xmlWriter.Close();

                    XmlDocument doc = new XmlDocument();                    //add to file
                    doc.Load("NetworkMonitor.xml");
                    foreach (NetworkLocation nl in LocationList)
                    {
                        XmlElement newlocation = doc.CreateElement("NetworkLocation");
                        XmlElement newname = doc.CreateElement("Name");
                        XmlElement newaddress = doc.CreateElement("Address");

                        newname.InnerText = nl.Name;
                        newaddress.InnerText = nl.Address;
                        newlocation.AppendChild(newname);
                        newlocation.AppendChild(newaddress);
                        doc.DocumentElement.AppendChild(newlocation);
                    }
                    XmlTextWriter tr = new XmlTextWriter("NetworkMonitor.xml", null);
                    tr.Formatting = Formatting.Indented;
                    doc.WriteContentTo(tr);
                    tr.Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not save entries while closing form", "Network Monitor", MessageBoxButtons.OK);
                }
            }
            else if (rs == DialogResult.No)
            {
                this.WindowState = FormWindowState.Minimized;
                this.MainForm_Resize(this, null);
            }
            else
                e.Cancel = true;
        }

        private void ApplicationNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                ApplicationNotifyIcon.Visible = true;
                ApplicationNotifyIcon.ShowBalloonTip(200);
                this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                ApplicationNotifyIcon.Visible = false;
            }
        }

        private void ShowLogButton_Click(object sender, EventArgs e)
        {
            if (File.Exists(Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("ddMMyyyy") + ".log"))
            {
                Process showlog = new Process();
                showlog.StartInfo.FileName = "notepad.exe";
                showlog.StartInfo.Arguments = Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("ddMMyyyy") + ".log";
                showlog.Start();
            }
            else
                MessageBox.Show("No Log created for today. Try again later.", "Network Monitor", MessageBoxButtons.OK);

        }

        private void RemoveLocationButton_Click(object sender, EventArgs e)
        {
            try
            {
                int index = LocationListView.SelectedIndices[0];

                LocationList.RemoveAt(index);
            }
            catch (Exception)
            {
                MessageBox.Show("Select a location from the list and then click Remove", "Network Monitor", MessageBoxButtons.OK);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            writer.WriteLine("Application started at " + DateTime.Now);

            XmlDocument doc = new XmlDocument();
            doc.Load("NetworkMonitor.xml");
            XmlNodeList nodelst = doc.GetElementsByTagName("NetworkLocation");
            foreach (XmlNode nd in nodelst)
            {
                this.AddNetworkLocation(nd.FirstChild.InnerText, nd.LastChild.InnerText);
            }

            PingSender.Priority = ThreadPriority.BelowNormal;
            PingSender.Start();
        }

    }
}





LogWriter。 cs



LogWriter.cs

using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;

namespace NetworkMonitor
{
    public class LogWriter
    {
        private List<String> _messagelist;
        private Thread _writer;

        public LogWriter()
        {
            _messagelist = new List<String>();
            _writer = new Thread(WriteAsync);

            _writer.Start();
        }

        public void WriteLine(String message)
        {
            if (message.ToString().Length > 0)
            {
                _messagelist.Add(message);
            }
        }

        public void Stop()
        {
            _writer.Abort();
        }

        private void WriteAsync()
        {
            try
            {

                while (true)
                {
                    try
                    {

                        String filename = Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("ddMMyyyy") + ".log";
                        if (!File.Exists(filename))
                            File.Create(filename);

                        using (StreamWriter writer = new StreamWriter(filename,true))
                        {
                            String[] messagelistcopy = _messagelist.ToArray();
                            _messagelist.Clear();

                            foreach (String msg in messagelistcopy)
                            {
                                writer.WriteLine(msg);
                            }
                            writer.Flush();
                        }
                    }
                    catch (Exception)
                    {
                        //do nothing
                    }

                }
            }
            catch (Exception)
            {
                //do nothing
            }
        }
    }
}

推荐答案

你完全没有任何线程同步。



自己说明涉及多少线程以及线程之间共享的实例。



例如 LogWrite.WriteLine 通过多个线程调用,导致无保护的 _messagelist 访问。这一切都只是时间问题,直到坏事发生。

_messagelist 内部线程也在内部无保护地修改为 WriteLine 电话。



与应用程序其余部分类似的问题。



如果使用线程,则必须具有明确的线程架构(正在运行的线程数,它们共享的数据)以及明确的锁定架构(必须保护哪些数据不受并发修改)。例如。用所有线程和所有共享对象绘制序列图。



干杯

Andi
You are completely missing any thread synchronization.

Make yourself a picture how many threads are involved and which instances are shared between the threads.

E.g. LogWrite.WriteLine is called over multiple threads leading to unprotected _messagelist access. This allone is just a matter of time until bad things happen.
_messagelist is also internally unprotectedly modified by the internal thread concurently to the WriteLine calls.

Similar issues with the rest of the application.

If playing with threads, you must have a clear threading schema (how many threads are running, what data do they share) and a clear locking schema (what data must be protected from concurrent modification). E.g. draw sequence diagrams with all threads and all shared objects.

Cheers
Andi


using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Threading;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Windows.Forms;
using CodeProjectSamples;

namespace NetworkMonitor
{
    public partial class MainForm : Form
    {
        private List<NetworkLocation> LocationList;
        private ListView LocationListView;
    
        private delegate void nlss(NetworkLocation nl);
        private Thread PingSender;

        LogWriter writer;
        public MainForm()
        {
            writer = new LogWriter();
            InitializeComponent();
            LocationList = new List<NetworkLocation>();
            PingSender = new Thread(this.CheckIpAsync);
            AddNetworkLocation("localhost", "127.0.0.1");
            PingSender.Start();
        }

        public bool AddNetworkLocation(string name, string address)
        {
            NetworkLocation temp;

            if (name.Length == 0)
            {
                MessageBox.Show("Enter a name", "Network Monitor", MessageBoxButtons.OK);
                return false;
            }
            else if (!ValidIp(address))
            {
                MessageBox.Show("Enter a valid ip/hostname", "Network Monitor", MessageBoxButtons.OK);
                return false;
            }

            temp = new NetworkLocation(name, address);
            LocationList.Add(temp);
            return true;
        }

        private bool ValidIp(string address)
        {
            string[] parts = address.Split(new char[] { ''.'' }, StringSplitOptions.None);

            if (parts.Length != 4)
                return false;
            else if (parts[0].Length == 0 || parts[1].Length == 0 || parts[2].Length == 0 || parts[3].Length == 0)
                return false;
            else
            {
                try
                {
                    int a, b, c, d;

                    a = int.Parse(parts[0]);
                    b = int.Parse(parts[1]);
                    c = int.Parse(parts[2]);
                    d = int.Parse(parts[3]);

                    if ((a < 0 || a > 255) || (b < 0 || b > 255) || (c < 0 || c > 255) || (d < 0 || d > 255))
                        return false;
                    else
                        return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        public void CheckIpAsync()
        {
            try
            {
                while (true)
                {
                 
                    NetworkLocation[] all_locations = new NetworkLocation[LocationList.Count];

                    LocationList.CopyTo(all_locations);
                    foreach (NetworkLocation nl in all_locations)
                    {
                        this.BeginInvoke(new nlss(this.NetworkLocationSetStatus), new Object[] { nl });
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception)
            {
                
            }
        }

        public void NetworkLocationSetStatus(NetworkLocation nl)
        {
            try
            {
                Ping ipchecker = new Ping();
                PingReply reply = ipchecker.Send(nl.Address, 1000);

                if (reply.Status == IPStatus.Success && nl.IsAlive == false)
                {
                    MessageBox.Show(nl.Name + "[" + nl.Address + "] went alive at " + DateTime.Now);
                    writer.WriteLine(nl.Name + "[" + nl.Address + "] went alive at " + DateTime.Now);
                    
                    nl.IsAlive = true;
                }
                else if (reply.Status != IPStatus.Success && nl.IsAlive == true)
                {
                    writer.WriteLine(nl.Name + "[" + nl.Address + "] went dead at " + DateTime.Now);
                    nl.IsAlive = false;
                }
            }
            catch (Exception)
            {
                writer.WriteLine(nl.Name + "[" + nl.Address + "] went dead at " + DateTime.Now);
            }
        }

        private void AddLocationButton_Click(object sender, EventArgs e)
        {
           // AddLocation f = new AddLocation(this);
            //f.ShowDialog();
        }

        private void AboutButton_Click(object sender, EventArgs e)
        {
            //NetworkMonitorAboutBox f = new NetworkMonitorAboutBox();
            //f.ShowDialog();
        }

        private void Watchmantimer_Tick(object sender, EventArgs e)
        {
            int index = -1;

            try
            {
                index = LocationListView.SelectedIndices[0];
            }
            catch (Exception)
            {
            }
            finally
            {
                LocationListView.Items.Clear();

                foreach (NetworkLocation l in LocationList)
                {
                    ListViewItem li = LocationListView.Items.Add(l.Name);
                    li.SubItems.Add(l.Address);
                    li.ImageIndex = l.IsAlive ? 0 : 1;
                }

                if (index >= LocationListView.Items.Count)
                    index = -1;

                if (index != -1)
                    LocationListView.Items[index].Selected = true;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult rs = MessageBox.Show("Click Yes to close application \nClick No to minimize\n& Click Cancel to close this dialog", "Network Monitor", MessageBoxButtons.YesNoCancel);

            if (rs == DialogResult.Yes)
            {
                if (PingSender.IsAlive)
                {
                    PingSender.Abort();
                }

                try
                {
                    File.Delete("NetworkMonitor.xml");

                    XmlTextWriter xmlWriter = new XmlTextWriter("NetworkMonitor.xml", System.Text.Encoding.UTF8);
                    //creating XmlTestWriter, and passing file name and encoding type as argument
                    xmlWriter.Formatting = Formatting.Indented;
                    //setting XmlWriter formating to be indented
                    xmlWriter.WriteProcessingInstruction("xml", "version=''1.0'' encoding=''UTF-8''");
                    //writing version and encoding type of XML in file.
                    xmlWriter.WriteStartElement("NetworkLocationList");
                    //writing first element
                    xmlWriter.Close();

                    XmlDocument doc = new XmlDocument();                    //add to file
                    doc.Load("NetworkMonitor.xml");
                    foreach (NetworkLocation nl in LocationList)
                    {
                        XmlElement newlocation = doc.CreateElement("NetworkLocation");
                        XmlElement newname = doc.CreateElement("Name");
                        XmlElement newaddress = doc.CreateElement("Address");

                        newname.InnerText = nl.Name;
                        newaddress.InnerText = nl.Address;
                        newlocation.AppendChild(newname);
                        newlocation.AppendChild(newaddress);
                        doc.DocumentElement.AppendChild(newlocation);
                    }
                    XmlTextWriter tr = new XmlTextWriter("NetworkMonitor.xml", null);
                    tr.Formatting = Formatting.Indented;
                    doc.WriteContentTo(tr);
                    tr.Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not save entries while closing form", "Network Monitor", MessageBoxButtons.OK);
                }
            }
            else if (rs == DialogResult.No)
            {
                this.WindowState = FormWindowState.Minimized;
                this.MainForm_Resize(this, null);
            }
            else
                e.Cancel = true;
        }

        private void ApplicationNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                //ApplicationNotifyIcon.Visible = true;
                //ApplicationNotifyIcon.ShowBalloonTip(200);
                //this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                //ApplicationNotifyIcon.Visible = false;
            }
        }

        private void ShowLogButton_Click(object sender, EventArgs e)
        {
            if (File.Exists(Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("ddMMyyyy") + ".log"))
            {
                Process showlog = new Process();
                showlog.StartInfo.FileName = "notepad.exe";
                showlog.StartInfo.Arguments = Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("ddMMyyyy") + ".log";
                showlog.Start();
            }
            else
                MessageBox.Show("No Log created for today. Try again later.", "Network Monitor", MessageBoxButtons.OK);

        }

        private void RemoveLocationButton_Click(object sender, EventArgs e)
        {
            try
            {
                int index = LocationListView.SelectedIndices[0];

                LocationList.RemoveAt(index);
            }
            catch (Exception)
            {
                MessageBox.Show("Select a location from the list and then click Remove", "Network Monitor", MessageBoxButtons.OK);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            writer.WriteLine("Application started at " + DateTime.Now);

            XmlDocument doc = new XmlDocument();
            doc.Load("NetworkMonitor.xml");
            XmlNodeList nodelst = doc.GetElementsByTagName("NetworkLocation");
            foreach (XmlNode nd in nodelst)
            {
                this.AddNetworkLocation(nd.FirstChild.InnerText, nd.LastChild.InnerText);
            }

            PingSender.Priority = ThreadPriority.BelowNormal;
            PingSender.Start();
        }

        private void InitializeComponent()
        {
            this.LocationListView = new System.Windows.Forms.ListView();
            this.SuspendLayout();
            // 
            // LocationListView
            // 
            this.LocationListView.Location = new System.Drawing.Point(32, 27);
            this.LocationListView.Name = "LocationListView";
            this.LocationListView.Size = new System.Drawing.Size(504, 282);
            this.LocationListView.TabIndex = 0;
            this.LocationListView.UseCompatibleStateImageBehavior = false;
            // 
            // MainForm
            // 
            this.ClientSize = new System.Drawing.Size(669, 365);
            this.Controls.Add(this.LocationListView);
            this.Name = "MainForm";
            this.ResumeLayout(false);

        }

    }
}





The above is his main form and here is NetworkLocation class





The above is his main form and here is NetworkLocation class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CodeProjectSamples
{
  public class NetworkLocation
    {
        public string Address;
        public string Name;
        public bool IsAlive;

        public NetworkLocation(string name, string address)
        {
            this.Address = address;
            this.Name = name;
        }
    }
}







Now if you execute the code ( It crashed my system twice. So be careful), you will see that the MessageBox I have placed inside CheckIpAsync() never gets called. As against if you comment while(true), expectantly once the MessageBox will appear. Why?



OP assumes that by invoking CheckIpAsync from an Asynchronous callback aspect fixes everything for him. No. In LogWriter class there is a shared variable




Now if you execute the code ( It crashed my system twice. So be careful), you will see that the MessageBox I have placed inside CheckIpAsync() never gets called. As against if you comment while(true), expectantly once the MessageBox will appear. Why?

OP assumes that by invoking CheckIpAsync from an Asynchronous callback aspect fixes everything for him. No. In LogWriter class there is a shared variable

_messagelist

.



So every time you call WriteLine() you are trying to write in _messagelist.结果? Two asynchronous instances at some instance will write to access the _messagelist memory.



Now do a simple test:



Change the foreach statement with



.

So every time you call WriteLine() you are trying to write in _messagelist. Result? Two asynchronous instances at some instance will write to access the _messagelist memory.

Now do a simple test:

Change the foreach statement with

this.Invoke((MethodInvoker)delegate
                        {
                            this.BeginInvoke(new nlss(this.NetworkLocationSetStatus), new Object[] { nl });
                        });







You will see many instances of MessageBox. So either you need to use a BackgroundWorker and modify your while with that or take a timer and call CheckIpAsync from timer tick ( no while remember). In either cases protect _messagelist by proper locking ( eg. above code).



In my discussion in comments I took an example of Label because UI elements are better way of understanding the flow of your execution. calling BeginInvoke from a loop with a shared variable is as good as calling it serially due to lock problem.




You will see many instances of MessageBox. So either you need to use a BackgroundWorker and modify your while with that or take a timer and call CheckIpAsync from timer tick ( no while remember). In either cases protect _messagelist by proper locking ( eg. above code).

In my discussion in comments I took an example of Label because UI elements are better way of understanding the flow of your execution. calling BeginInvoke from a loop with a shared variable is as good as calling it serially due to lock problem.


the problem lay elsewhere. the ui became unresponsive only when there was a unreachable node in the addresslist. this happened beacause my code was somewhat like this



the problem lay elsewhere. the ui became unresponsive only when there was a unreachable node in the addresslist. this happened beacause my code was somewhat like this

public void CheckIpAsync()
        {
            try
            {       
                while (true)
                {
                    NetworkLocation[] all_locations = new NetworkLocation[LocationList.Count];
 
                    LocationList.CopyTo(all_locations);
                    foreach (NetworkLocation nl in all_locations)
                    {
                        this.BeginInvoke(new nlss(this.NetworkLocationSetStatus), new Object[] { nl });
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception)
            {
                writer.WriteLine("IP checking stopped at " + DateTime.Now);
                writer.WriteLine("-------------------------------------------------------------------");
                writer.Stop();
            }            
        }
 
        public void NetworkLocationSetStatus(NetworkLocation nl)
        {            
            try
            {
                Ping ipchecker = new Ping();
                PingReply reply = ipchecker.Send(nl.Address, 1000);
 
                if (reply.Status == IPStatus.Success && nl.IsAlive == false)
                {
                    writer.WriteLine(nl.Name + "[" + nl.Address + "] went alive at " + DateTime.Now);
                    nl.IsAlive = true;
                }
                else if (reply.Status != IPStatus.Success && nl.IsAlive == true)
                {
                    writer.WriteLine(nl.Name + "[" + nl.Address + "] went dead at " + DateTime.Now);
                    nl.IsAlive = false;
                }
            }
            catch (Exception)
            {
                writer.WriteLine(nl.Name + "[" + nl.Address + "] went dead at " + DateTime.Now);
            }
        }



now the thread method kept on submitting asynchronous begininvokes of NetworkLocationSetStatus(NetworkLocation nl) irrespective of how much time it took to finish up(a dead node takes up considerable time to finish up i.e. being declared dead). hence calls for NetworkLocationSetStatus(deadnode) kept piling up asnchronously and soon everything went haywire.



Solution was just to change the BeginInvoke to Invoke. that way the thread remains locked till NetworkLocationSetStatus() method finishes up and then the loop moves onto the next node.



Lesson learnt. And asynchronous methods are not all that great if you don’’t know what u are doing. For novice programmers like me, synchronous rocks (though its slow).



Thanks everybody for your support. Thanks a lot.


now the thread method kept on submitting asynchronous begininvokes of NetworkLocationSetStatus(NetworkLocation nl) irrespective of how much time it took to finish up(a dead node takes up considerable time to finish up i.e. being declared dead). hence calls for NetworkLocationSetStatus(deadnode) kept piling up asnchronously and soon everything went haywire.

Solution was just to change the BeginInvoke to Invoke. that way the thread remains locked till NetworkLocationSetStatus() method finishes up and then the loop moves onto the next node.

Lesson learnt. And asynchronous methods are not all that great if you don''t know what u are doing. For novice programmers like me, synchronous rocks (though its slow).

Thanks everybody for your support. Thanks a lot.


这篇关于C#程序变得反应迟钝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆