在C#中捕获内存不足异常
作者:conan 发布时间:2021-07-14 11:50:46
标签:C#,捕获,内存,异常
当CLR未能分配所需的足够内存时,将发生System.OutOfMemoryException
。System.OutOfMemoryException
继承自System.SystemException
类。OutOfMemoryException
使用COR_E_OUTOFMEMORY
值为 0x8007000E的 HRESULT 。
一个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);
来源:https://mp.weixin.qq.com/s?__biz=Mzg3ODAxNzM5OQ==&mid=2247493678&idx=1&sn=0edf9083eb1326d6a86e52ef454fe9d3&utm_source=tuicool&utm_medium=referral


猜你喜欢
- 方法一:Convert.ToDateTime(string)string格式有要求,必须是yyyy-MM-dd hh:mm:ss方法二:Co
- 本文实例讲述了C#实现图像锐化的方法。分享给大家供大家参考。具体如下://定义图像锐化函数private static Bitmap Sha
- Android 自定义标题栏的实例详解开发 Android APP 经常会用到自定义标题栏,而有多级页面的情况下还需要给自定义标
- Java中,for-each循环简化了任何Collection或array的遍历过程,但并不是每个Java程序员都了解本文将要描述的for-
- 1、conditional注解介绍含义: 基于条件的注解作用: 根据是否满足某一个特定条件来决定是否创建某个特定的bean意义: Sprin
- 排列组合是常见的数学问题,本文就以完整实例形式讲述了C#实现排列组合算法的方法。分享给大家供大家参考之用。具体方法如下:首先,数学中排列组合
- 本文主要讲解利用android中Matrix控制图形的旋转缩放移动,具体参见一下代码:/** * 使用矩阵控制图片移动、缩放、旋
- 本文以实例形式简单讲述了引用类型转换的几种常见方式,如:子类转换成父类,父类转换成子类,以及不是子父级关系类之间的转换。现分述如下,供大家参
- 基本概念:类加载的过程大致分为三个阶段1、加载阶段:本阶段主要把class的二进制代码加载进入JVM,并且进行常量池(类名,方法名,字段名)
- 闲来无事,刚学会把git部署到远程服务器,没事做,所以简单做了一个抓取网页信息的小工具,里面的一些数值如果设成参数的话可能扩展性能会更好!希
- 今天给大家提供一个由今天给大家提供一个由Java swing实现的酒店管理系统,数据库采用sqlserver,我会贴上部分代码,完整的代码请
- 在Android开发中,我们不光可以使用已有的实现方式,而且,我们还可以利用Android这个智能手机平台,实现一些比较有特色的功能。本篇文
- 一、Servlet3.0异步请求@WebServlet(value = "/async", asyncSupported
- 服务器端代码:import java.io.BufferedReader; import java.io.InputStreamR
- 接口等幂性通俗的来说就是同一时间内,发起多次请求只有一次请求成功;其目的时防止多次提交,数据重复入库,表单验证网络延迟重复提交等问题。比如:
- 简介区别String的缺点是每次字符串变量的内容发生了改变时,都必须重新分配内存。你想想,如果创建一个迭代100000次的循环,每次迭代都将
- 最近学习Spring,一直不太明白Srping的切面编程中的的argNames的含义,经过学习研究后,终于明白,分享一下需要监控的类:pac
- 这节主要完成一些基本的增删改查以及Service、Dao和Action的抽取。1. Service层的抽取  
- Swing组件中的事件处理专门用于响应用户的操作,例如,响应用户的鼠标单击、按下键盘等操作。在Swing事件处理的过程中,主要涉及三类对象:
- 第一步:配置管理器中新建解决方案配置第二步:定义条件编译符号:第三步:在代码中使用自定义的条件编译#if CustomDebugConsol