2016-07-03 27 views
0
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace OcppDummyClient 
{ 
    public partial class Form1 : Form 
    { 
     public string[] messages = new string[] 
     { 
      "Authorize", 
      "BootNoficiation" 
     }; 

     public Panel A; 
     public Panel B; 

     public Form1() 
     { 
      InitializeComponent(); 
      InitializeForm(); 

      A = new Panel() 
      { 
       Width = this.flowLayoutPanel1.Width, 
       Height = this.flowLayoutPanel1.Height, 
       BackColor = Color.Black 
      }; 

      A.Controls.Add(new Button() 
      { 
       Text = "Button" 
      }); 

      B = new Panel() 
      { 
       Width = this.flowLayoutPanel1.Width, 
       Height = this.flowLayoutPanel1.Height, 
       BackColor = Color.Blue 
      }; 

      B.Controls.Add(new Button() 
      { 
       Text = "Button2" 
      }); 

      this.flowLayoutPanel1.Controls.Add(A); 
      this.flowLayoutPanel1.Controls.Add(B); 
     } 

     public void InitializeForm() 
     { 
      this.comboBox1.Items.AddRange(messages); 
     } 

     private void comboBox1_SelectedValueChanged(object sender, EventArgs e) 
     { 
      string SelectedValue = this.comboBox1.Text.ToString(); 

      switch(SelectedValue) 
      { 
       case "Authorize": 
       { 
        A.Visible = true; 
        B.Visible = false; 
        break; 
       } 

       case "BootNoficiation": 
       { 
        A.Visible = false; 
        B.Visible = true; 
        break; 
       } 

       default: 
       { 
        break; 
       } 
      } 
     } 
    } 
} 

這就是我的全部代碼,我想知道爲什麼當我改變與組合框事件處理(comboBox1_SelectedValueChanged)的發生內存泄漏。我認爲內存泄漏沒有發生,因爲我已經創建了面板,只是改變了面板屬性(可見)。C#有內存泄漏時,面板屬性更改

+1

可能重複的[爲什麼右鍵單擊在圓的中心創建一個橙點?](http://stackoverflow.com/questions/12692851/why-does-right-clicking-create-an-orange -dot-in-the-the-the-circle) – KeyWeeUsr

+2

你爲什麼認爲有內存泄漏? – Chris

+0

我剛剛在Windows中打開任務管理,並做了一些更改的組合框事件,我的程序內存增加了! – user3773632

回答

1

內存增加並不表示受管內存中存在內存泄漏。內存只會在回收垃圾時被回收。在此之前內存使用量會增加。當應該被垃圾收集的對象不是真的死的時候(因爲有一些意想不到的活動引用),會發生內存「泄漏」。

話雖如此,你仍應該小心WinForms控件。因爲它們實際上包裝了本地Windows控件,所以它們聲稱來自Windows的控制句柄。調用控件的Dispose方法時釋放此句柄。這可以(並且在大多數情況下)在垃圾收集期間發生,但在那之前該句柄不會返回到窗口(並且在垃圾收集期間沒有100%的保證)。爲避免資源從太多打開的Windows句柄中泄漏,您應該在不再需要時立即丟棄WinForms控件。

處置Control也將處理其Controls集合中的所有子控件。既然您將兩個面板都添加到該集合中,那麼您在那裏也可能很安全。