finally is not executed when calling Thread.Abort

215 views Asked by At

Does anyone know a reason why finally statement wouldn't be executed when calling Thread.Abort? I have thread function like this:

void ThreadFunc()
{
    try
    {
        int counter = 0;
        while (true)
        {
            Debug.Log ("Waiting" + counter);
            Thread.Sleep(100);
            ++counter;
        }
        Debug.Log("Success.");
    }
    catch(ThreadAbortException ex)
    {
        Debug.LogWarning("Cancelled: " + ex);
    }
    catch(System.Exception ex)
    {
        Debug.LogError("Error: " + ex);
    }
    finally
    {
        Debug.Log("Finally");
    }
}

I terminate this thread using Thread.Abort. All I see in output is a bunch of Waiting, but no other lines. My main thread keeps running after calling Thread.Abort (i.e. child thread has enough time to complete). Debug.Log functions are thread safe.

This happens on Windows. I'm using Mono (Unity game engine). On Mac it works fine. On iOS I get this behavior, but it seems to depend on device/iOS version or XCode version (I haven't figured out yet). On Windows it happens every time.

BTW: on iOS it crashes if I put another try {} catch {} into finally statement.

Is anyone aware why this is happening? It seems to be quite different from what the documentation of Thread.Abort and ThreadAbortException says.

1

There are 1 answers

0
Sergey Zhukov On BEST ANSWER

Mono does not support Constrained Execution Regions and does not fully support catch/finally when Thread.Abort is called.

There is a bug about this.