C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#捕获内存异常

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

作者:conan

这篇文章主要介绍了在C#中捕获内存不足异常,下面文章内容围绕如何在C#中捕获内存不足异常的相关资料展开详细内容,具有一定的参考价值,需要的小伙伴可以参考一下,希望对你有所帮助

当CLR未能分配所需的足够内存时,将发生System.OutOfMemoryExceptionSystem.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);

到此这篇关于在C#中捕获内存不足异常的文章就介绍到这了,更多相关C#捕获内存异常内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文