在引发OutOfMemoryException之前调用GC.Collect [英] Call GC.Collect Before Throwing OutOfMemoryException
问题描述
在抛出OutOfMemoryException之前有什么方法可以让GC.Collect()被调用吗?
Is there any way to get GC.Collect() to be called before throwing an OutOfMemoryException?
我想我正在寻找一种方法来执行以下代码流:
I suppose I'm looking for a way for it to do the following code flow:
Try to Allocate Memory
On Pass Return
Call GC.Collect()
Try to Allocate Memory
On Fail Throw New OutOfMemoryException()
我正在编写一个缓存实现,目前正在遇到内存异常,因此当前正在使用以下方法解决它:
I'm writing a caching implementation and currently I'm running into memory exceptions so currently to resolve it I am using:
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扔到一个循环中,直到尝试完成任务并确保它具有清理自身的能力为止.
Maybe I'm not understanding your question, but wouldn't it be possible for you to just catch OutOfMemoryException's thrown and call GC.Collect there? Toss the try/catch inside a loop that continues until you've finished your task and make sure it has the ability to clean itself up.
bool isFinished = false;
while (isFinished) {
try {
// do operations in here
} catch (OutOfMemoryException oom) {
GC.Collect();
}
// if you're done...
isFinished = true;
}
请原谅使用C#伪代码代替VB,除非没有其他选择,否则我尽量不要在VB中工作.
Pardon the use of C# pseudo instead of VB, I try not to work in VB unless I have no choice.
这篇关于在引发OutOfMemoryException之前调用GC.Collect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!