简体   繁体   中英

How to reduce memory usage of a windows form application in C# VS 2010 Professional

I have an application with a simple gui, very few graphics but a lot of objects ie. labels text boxes and a few panels.
On some panels it runs LDAP queries, in others it queries processes running and checks NIC status.
When I go to the LDAP searcher panel, memory usage drops down to app 30mb, when I return to the main panel that only runs a timer, It jumps to about 300mb + then keeps accumulating, I run GC.Collect() as often as I can, on minimize after primary methods have been run and such still to no effect, ive used optimize code under build in project properties and ive stripped out all of the Using system.whatever. I am a reasonably new programmer, its only been about 6 months since I started doing windows forms. Any help would be nice. My application is essentially a GUI that sits there with a timer running in the background, then does the aforementioned queries and some task skills. Nothing too memory intensive. Could the gui objects themselves be eating up my memory?

    public MainMethod()
    {
        try
        {

            InitializeComponent();

            notifyIcon1.Visible = true;


            // this.Opacity = .5;
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 1000 * 10;

            pword();
            this.ShowInTaskbar = false;
            this.Hide();
            this.Visible = false;
           // GC.Collect();
        }
        catch (Exception ex)
        {
            eventWriter(ex);
        }

    }
    public void pword()
    {
        try
        {

            bool nCheck;
            string[] infoArray = new string[4];
            nCheck = checker.checkNetwork();
            int dayNum = 0;

            if (nCheck == true)
            {

                infoArray = checker.checkAD();   //this is similar code to CheckNetwork except it returns values from the user's AD account properties.
                label3.Text = infoArray[0];
                label2.Text = infoArray[2];
                label1.Text = infoArray[3];
                label21.Text = infoArray[0];
                label22.Text = infoArray[1];
                label23.Text = infoArray[2];
                label24.Text = infoArray[3];
                days = infoArray[3];
                dayNum = int.Parse(days);
                if (dayNum <= 15)
                {
                    timedIntervalChanger(2);
                    aTimer.Start();
                    GC.Collect();
                }
            }
            else
            {
                timedIntervalChanger(1);
                aTimer.Start();
                GC.Collect();
            }
        }
        catch (Exception ex)
        {
            eventWriter(ex);
        }

} public bool checkNetwork() { bool connected; try {

            String objectName = WindowsIdentity.GetCurrent().Name;


            if (objectName.Contains("administrator"))
            {
                connected = false;
                return connected;
            }

            else
            {





                // Sets domain
                string LdapDomain = "mydomain.com"
                //Sets properties for directory Entry and Searcher
                string connectionPrefix = "LDAP://" + LdapDomain;
                DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
                DirectorySearcher mySearcher = new DirectorySearcher(entry);


                mySearcher.Filter = "(&(objectClass=user)(objectCategory=Person)(|(cn=" + objectName + ")(sAMAccountName=" + objectName + ")))";

                //instantiates result object from the search

                SearchResult LDAPresult = mySearcher.FindOne();

                entry = LDAPresult.GetDirectoryEntry();
                connected = true;

            }
            return connected;
        }
        catch
        {
            connected = false;
            return connected;
        }
    }
    public void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        try
        {

            notifyIcon1.Visible = true;
            notifyIcon1.ShowBalloonTip(1000 * 9, "Test", "test text", ToolTipIcon.Warning);


         pword();
        }
        catch (Exception ex)
        {
            eventWriter(ex);
        }


    }

It's when I show the form that the memory usage jumps tremendously. Each method is independant and I left out some of the object instantiation code.

We really need more info here. But a few suggestions:

  1. Use the using keyword or call Dispose() on all disposable objects when you are done with them
  2. Make sure you unregister event handlers when you are done listening for events

I am not sure what LDAP library you are using but in System.DirectoryServices many of the classes (like DirectoryEntry ) implement IDisposable and can 'leak' if they are not disposed of

使用“分析”菜单中的“性能向导”的“.NET内存分配”选项创建性能会话,该会话将帮助您确定需要在代码中进行哪些更改以减少内存使用量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM