I'm using a constrained execution region (CER) to protect the section of code within a while loop of a thread:
private static void MyThreadFunc()
{
try {
...
while (true)
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
// do something not to be aborted
}
Thread.Sleep(1); // allow while loop to be broken out
}
}
catch (ThreadAbortException e)
{
// handle the exception
}
}
The problem is if I do not introduce the Thread.Sleep(1)
statement at the end of the while loop, any attempt to call Thread.Abort() on the thread hangs. Is there any better method to abort the thread without using the Thread.Sleep()
function?