C#如何立即回收内存

1.把对象赋值为null
2.立即调用GC.Collect();

注意:这个也只是强制垃圾回收器去回收,但具体什么时候执行不确定。 

代码:

  public partial class Form1 : Form
    {
        [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet =System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true)]
        private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int maximumWorkingSetSize);


        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            ClearMemory();
        }


        #region 内存回收
   public  void ClearMemory()
 {
     GC.Collect();
     GC.SuppressFinalize(this);


     if (Environment.OSVersion.Platform == PlatformID.Win32NT)
     {
         SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
     }
 }
 #endregion


   private void timer1_Tick(object sender, EventArgs e)
   {
       string s="clearMemory";
       Form dt = new Form();
        dt.Text = s;
       //如果垃圾产生于timer中可能无法立刻回收资源,需加载timer tick事件中,立刻回收资源,或使用另外的timer控制回收时间。
       GC.Collect();
   }
 
    }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值