When does ExecuteCodeWithGuaranteedCleanup actually guarantee cleanup?

I read about Reliability Functions in .NET and wrote the following class to learn ExecuteCodeWithGuaranteedCleanup

 class Failing { public void Fail() { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(Code, Cleanup, "fail"); } } private void Code(object message) { // Some code in here that will cause an exception... } private void Cleanup(object message, bool something) { Console.WriteLine(message); Console.ReadLine(); } } 

I experimented with various code bodies for the Code method. These and their results are indicated below.

Causing OutOfMemoryException - Cleanup does not raise

 List<string> ss = new List<string>(); while (true) { string s = new string('x', 1000000); ss.Add(s); } 

Causing StackOverflowException - Cleanup Does Not Call

 Code(message); // recursive call 

Causing ExecutionEngineException - Cleanup Does Not Call

 Environment.FailFast(message.ToString()); 

Raises a call to ThreadAbortException - Cleanup does (however a regular try...finally can also catch this exception)

 Thread.CurrentThread.Abort(); 

So the questions are:

  • Am I using ExecuteCodeWithGuaranteedCleanup ?
  • When is ExecuteCodeWithGuaranteedCleanup really useful?
+7
reliability
source share
1 answer

Some exceptions are fatal to the process, and the execution of the code provided by the user simply does not continue. The purpose of the ExecuteCodeWithGuaranteedCleanup method is to let you put your data structures in a consistent state. If the process dies in any case without the possibility of stopping it, this has no purpose. The OS (provided that it works correctly) will automatically clean up any kernel objects when the process terminates, regardless of the reason for the termination of the process.

As Hans hints, a host ICLRPolicyManager comes into play to determine which exceptions are fatal in such a way when the code runs on a specific host (especially in SQL Server). See Good Grid at the bottom of the documentation page: ICLRPolicyManager :: SetActionOnFailure Method

+2
source share

All Articles