我正在尝试追踪当我对 C# 代码施加压力并在低内存条件下运行时发生的崩溃。但是,在某些情况下,我的程序不会出现 OutOfMemoryException,而是会崩溃并退出。这通常是由缓冲区溢出或堆栈溢出(或损坏)引起的内存损坏引起的。
那么,有没有办法检查堆的完整性,或者有没有办法检查线程上还剩下多少堆栈?
出于速度原因,我使用了很多不安全的代码,所以很可能我的代码在某处破坏了内存。不幸的是,崩溃发生在损坏发生后的随机时间间隔内。我知道 C# 会在检测到缓冲区溢出时关闭应用程序,但有没有办法强制它进行检查?
谢谢。
最佳答案
您可以使用 Constrained Execution Regions 处理这些情况:
A constrained execution region (CER) is part of a mechanism for authoring reliable managed code. A CER defines an area in which the common language runtime (CLR) is constrained from throwing out-of-band exceptions that would prevent the code in the area from executing in its entirety. Within that region, user code is constrained from executing code that would result in the throwing of out-of-band exceptions. The
PrepareConstrainedRegions
method must immediately precede atry
block and markscatch
,finally
, andfault
blocks as constrained execution regions. Once marked as a constrained region, code must only call other code with strong reliability contracts, and code should not allocate or make virtual calls to unprepared or unreliable methods unless the code is prepared to handle failures. The CLR delays thread aborts for code that is executing in a CER.
当然,CER 的限制非常多。你不能在他们身上做太多。它们专为关键的小部分代码而设计。
关于c# - 在 C# 中检查堆完整性和堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1638000/