服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 在C#中捕获内存不足异常

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

2022-12-14 12:09conan C#

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

当CLR未能分配所需的足够内存时,将发生System.OutOfMemoryExceptionSystem.OutOfMemoryException继承自System.SystemException类。OutOfMemoryException使用COR_E_OUTOFMEMORY值为 0x8007000E的 HRESULT 。

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

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

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

设置字符串-

?
1
2
string StudentName = "Tom";
string StudentSubject = "Maths";

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

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

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

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

发生以下异常-

?
1
System.OutOfMemoryException: Out of memory

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

示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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:

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

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

原文链接:https://mp.weixin.qq.com/s?__biz=Mzg3ODAxNzM5OQ==&mid=2247493678&idx=1&sn=0edf9083eb1326d6a86e52ef454fe9d3&utm_source=tuicool&utm_medium=referral

延伸 · 阅读

精彩推荐