(WeakReference )弱引用解决OutOfMemoryException异常

本文通过对比使用直接创建大对象与使用WeakReference创建大对象的方法,展示了如何利用WeakReference来减轻长时间占用内存的大对象带来的负担,有效避免内存溢出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用WeakReference 来释放那些长时间在内存中无用的大对象

测试代码:

 

View Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
namespace WeakReferenceTestSample
{
    public class SomeBigClass : List<string>
    {

        public SomeBigClass()
        {
            //this.LoadBigObject();
            this.LoadWeakReferenceBigObject();
        }

        private void LoadBigObject()
        {
            var smallBlockSize = 90000;
            var largeBlockSize = 1 << 24;
            var count = 0;
            var bigBlock = new byte[0];
            //for (int i = 0; i < 100000; i++)
            //    this.Add(string.Format("String No. {0}", i));
            try
            {
                var smallBlocks = new List<byte[]>();
                while (true)
                {
                    GC.Collect();
                    bigBlock = new byte[largeBlockSize];
                    largeBlockSize++;
                    smallBlocks.Add(new byte[smallBlockSize]);
                    count++;
                    Console.WriteLine("{0} {1}", count.ToString(), ObjectSize(smallBlocks).ToString());
                }
            }
            catch (OutOfMemoryException)
            {
                bigBlock = null;
                GC.Collect();
                Console.WriteLine("{0} Mb allocated",
                                  (count*smallBlockSize)/(1024*1024));
            }
        }

        private void LoadWeakReferenceBigObject()
        {
            var smallBlockSize = 90000;
            var largeBlockSize = 1 << 24;
            var count = 0;
            //var bigBlock = new byte[0];
            var bigBlock = new WeakReference(new byte[0]);
            try
            {
                //var smallBlocks = new List<byte[]>();
                var smallBlocks = new List<WeakReference>();
                while (true)
                {
                    GC.Collect();
                    bigBlock = new WeakReference(new byte[largeBlockSize]);
                    largeBlockSize++;
                    smallBlocks.Add(new WeakReference(new byte[smallBlockSize]));
                    count++;
                    Console.WriteLine("{0} {1}", count.ToString(), ObjectSize(smallBlocks).ToString());
                }
            }
            catch (OutOfMemoryException)
            {
                bigBlock = null;
                GC.Collect();
                Console.WriteLine("{0} Mb allocated",
                    (count * smallBlockSize) / (1024 * 1024));
            }
        }

        private long ObjectSize(object o)
        {
            long size = 0;
            //object o = new object();
            using (Stream s = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(s, o);
                size = s.Length;
            }
            return size;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值