Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Finally vs Thread.BeginCriticalRegion

As I understand it, a finally block must be completed before a thread abort can take effect. For what purpose should Thread.BeginCriticalRegion be used instead, risking termination of the appdomain?

Example:

try
{
}
finally
{
    CriticalOperation();
}

or

Thread.BeginCriticalRegion();
CriticalOperation();
Thread.EndCriticalRegion();
like image 808
toplel32 Avatar asked Sep 29 '22 15:09

toplel32


1 Answers

To make it very simple, try... finally... do protect against Thread.Abort (the finally part is fully protected and can't be interrupted/will always be executed), while Thread.BeginCriticalRegion() only give some metainformation to the runtime of .NET:

From https://docs.microsoft.com/nl-nl/archive/blogs/bclteam/constrained-execution-regions-and-other-errata-brian-grunkemeyer

Critical regions don't really do much.

...

The first effect for critical regions is a way of informing the CLR that a lock is being held by a block of managed code

(note that this is only information... what the runtime does is its problem. There is no guarantee here)

The second effect is that memory allocations within that block of code are marked as appdomain-critical.

and then it explain that the runtime should give priority to memory allocation to that block of code... so other meta-information for the runtime without guarantees for the programmer

like image 171
xanatos Avatar answered Oct 05 '22 08:10

xanatos