在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#捕獲內存異常內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: