Friday 15 April 2011

C# - release memory when throwing exception, presumably no finally block -


In my C # app I'm throwing custom defined exceptions during the start of some very large arrays How can all leave the memory until the exception does not throw any gaps, unless an interval is left, the end does not block, but the throw statement? Or can finally be executed after throwing the block in this context?

Thanks

If you have a local array announcement, No need to pay attention because it will be collected by you for GC. So if your code looks like this:

  int [] value = new int [100000]; // Throw new applications exception (here) to some initialization; // something initialize here   

then you do not have to worry about it. The same applies to the case even if your array will be out of the scope of the variable, when the exception will be settled or after that it will be GC'ed the only problem is when you have a field variable in the class as Yes, that is not GC'ed itself (which means it will be referred to from somewhere else) or static field or similar. If you want to make sure it clears, you can do the following:

  try {m_Values ​​= new int [100000]; // Throw new applications exception (here) to some initialization; // some initially illustrated} hold // Use this part if there is no exception, then the array should be used {m_Values ​​= null; throw; } Finally // Use this part if you do not need an array later {m_Values ​​= null; }   

So if you use this method, then you can ensure that there will be no reference for your array and it will collect garbage at some point. You can force GC to collect it but it has not been recommended.

No comments:

Post a Comment