Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call GC.Collect Before Throwing OutOfMemoryException

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
like image 465
Seph Avatar asked Feb 21 '26 06:02

Seph


1 Answers

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;
}

Pardon the use of C# pseudo instead of VB, I try not to work in VB unless I have no choice.

like image 86
AndyM84 Avatar answered Feb 24 '26 00:02

AndyM84



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!