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
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.
Pardon the use of C# pseudo instead of VB, I try not to work in VB unless I have no choice.