有什么方法可以让 GC.Collect() 在抛出 OutOfMemoryException 之前被调用?
我想我正在寻找一种方法让它执行以下代码流:
Try to Allocate Memory
On Pass Return
Call GC.Collect()
Try to Allocate Memory
On Fail Throw New OutOfMemoryException()
我正在编写一个缓存实现,目前我遇到了内存异常,所以目前为了解决它,我正在使用:
If GC.GetTotalMemory(False) >= cache.CacheMemoryLimit + (100 * 1024 * 1024) Then
// When Total Memory exceeds CacheMemoryLimit + 100MB
GC.Collect()
End If
最佳答案
也许我不理解您的问题,但您是否可以只捕捉到抛出的 OutOfMemoryException 并在那里调用 GC.Collect?将 try/catch 放入一个循环中,一直持续到您完成任务,并确保它能够 self 清理。
bool isFinished = false;
while (isFinished) {
try {
// do operations in here
} catch (OutOfMemoryException oom) {
GC.Collect();
}
// if you're done...
isFinished = true;
}
请原谅使用 C# pseudo 而不是 VB,除非别无选择,否则我尽量不使用 VB。
关于.net - 在抛出 OutOfMemoryException 之前调用 GC.Collect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4688348/