finally is not executed when calling Thread.Abort
Asked Answered
C

1

2

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.

Cyanic answered 20/11, 2014 at 21:56 Comment(0)
S
2

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.

Sandblast answered 20/11, 2014 at 23:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.