如何在C#中捕获内存不足异常?

当CLR未能分配所需的足够内存时,将发生System.OutOfMemoryException。System.OutOfMemoryException继承自System.SystemException类。OutOfMemoryException使用COR_E_OUTOFMEMORY值为 0x8007000E的 HRESULT 。有关OutOfMemoryException实例的初始属性值列表,请参阅OutOfMemoryException构造函数。

一个OutOfMemoryException异常异常主要有两个原因:

您试图将StringBuilder对象扩展到超出其StringBuilder.MaxCapacity属性定义的长度。

公共语言运行时无法分配足够的连续内存来成功执行操作。任何需要分配内存的属性分配或方法调用都可能引发此异常。

设置字符串-

string StudentName = "Tom";
string StudentSubject = "Maths";

现在您需要使用分配的容量进行初始化,该容量是初始值的长度-

StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);

现在,如果您尝试插入其他值,则会发生异常。

sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);

发生以下异常-

System.OutOfMemoryException: Out of memory

要捕获错误,请尝试以下代码-

示例

   try
            {
                
                string videoSaveDir = CommonHelper.GetVideoDirectory();
                int setCount = 0;
                #region 模拟抛出OutOfMemoryException用
                //List<VideoExtend> dataSource = new List<VideoExtend>();
                //dataSource.Add(new VideoExtend() {  EHost="http://www.baidu.com",FileName="BAI.mp4"});
                #endregion
                
                if (dataSource != null)
                {
                    totalCount = dataSource.Count;
                }
                foreach (VideoExtend video in dataSource)
                {
                    try
                    {
                        setCount++;
                        string fileName = video.FileName;
                        string fileFullPath = videoSaveDir + fileName;
                        if (File.Exists(fileFullPath))
                        {
                            if (!JudgeFileStatus(fileFullPath, fileName))
                            {
                                continue;
                            }
                            string strFileSize = "";
                            if (!FileCanUpload(fileFullPath, out strFileSize))
                            {
                                //数据库更新为上传失败,文件太大
                                if (mongoData == null)
                                {
                                    apiHelper.UpdateUploadToQiniuFileTooLarge(video.EHost);
                                }
                                else
                                {
                                    mongoData.UpdateUploadToQiniuFileTooLarge(video.EHost);

                                }
                                LogHelper.Log(LogFilePrefix+"uploadFileTooLarge", "文件" + fileName + "太大,大小为:" + strFileSize);
                                continue;
                            }
                            LogHelper.Log(LogFilePrefix + "uploadInfo", "开始上传" + setCount + "/" + totalCount + "文件:" + video.FileName);
                            string newFileName = "";
                            bool updateStatus = QiniuUtil.Upload(fileFullPath, out newFileName);
                            if (updateStatus)
                            {
                                if (mongoData == null)
                                {
                                    apiHelper.UpdateUploadToQiniuSuccessStatus(video.EHost, newFileName);
                                }
                                else
                                {
                                    mongoData.UpdateUploadToQiniuSuccessStatus(video.EHost, newFileName);//更新数据库
                                }

                                LogHelper.Log(LogFilePrefix + "uploadsuccess", "上传成功,源文件名:" + video.FileName + ";新文件名:" + newFileName);
                                if (JudgeFileStatus(fileFullPath, fileName))
                                {
                                    try
                                    {
                                        File.Delete(fileFullPath);
                                    }
                                    catch (Exception ex) { }
                                }
                                setCount++;
                            }
                        }
                        else
                        {
                            //把数据库重置为要重新下载
                            if (mongoData == null)
                            {
                                apiHelper.UpdateUploadToQiniuLocalFileNotFound(video.EHost);
                            }
                            else
                            {
                                mongoData.UpdateUploadToQiniuLocalFileNotFound(video.EHost);

                            }
                            LogHelper.Log(LogFilePrefix + "uploadNoExisted", "文件不存在:" + fileName);
                            //throw new System.OutOfMemoryException();//模拟抛出OutOfMemoryException用
                        }
                    }
                    catch (System.OutOfMemoryException memoryEx)
                    {
                        Global.IsOutOfMemoryException = true;
                        LogHelper.LogWithLock(LogFilePrefix + "uploadOutOfMemoryException", "失败,文件名" + video.FileName + ",异常信息:" + memoryEx.Message + ";内部错误" + memoryEx.InnerException?.Message);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Log(LogFilePrefix + "uploadError", "失败,文件名" + video.FileName + ",异常信息:" + ex.Message + ";内部错误" + ex.InnerException.Message);
                    }
                    System.Threading.Thread.Sleep(5 * 1000);//休眠
                }
                if (setCount <= 0)
                {
                    LogHelper.Log(LogFilePrefix + "uploadInfo", "暂无新待上传数据");
                }
                int sleepSecond = 30;
                LogHelper.Log(LogFilePrefix + "uploadInfo", "--休眠" + sleepSecond + "秒");
                System.Threading.Thread.Sleep(sleepSecond * 1000);//休眠
            }
            catch (Exception ex)
            {
                LogHelper.Log(LogFilePrefix + "uploadfullerror", "失败,异常信息:" + ex.Message+ ";totalCount="+ totalCount);
            }

上面处理OutOfMemoryException并生成以下错误-

输出结果

Error:

    Global.IsOutOfMemoryException = true;
                        LogHelper.LogWithLock(LogFilePrefix + "uploadOutOfMemoryException", "失败,文件名" + video.FileName + ",异常信息:" + memoryEx.Message + ";内部错误" + memoryEx.InnerException?.Message);

UP技术控

江东子弟多才俊,卷土重来未可知。——唐·杜牧

463篇原创内容

公众号

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值