Why is the last block * sometimes * not thrown in a ThreadAbortException if it contains a wait?

UPDATE: I don't think this question is a duplicate. Can a ThreadAbortException skip at last? , because (1) I am not creating another thread, therefore there is no possibility of a race condition, and (2) this behavior occurs only if the block finallycontains await, which is not mentioned in this other question.


Consider this console program:

class Program
{
    static void Main()
    {
        try { T().GetAwaiter().GetResult(); }
        catch (ThreadAbortException) { Thread.ResetAbort(); }
        catch { }
    }

    static async Task Abort()
    {
        //await Task.Delay(1); // A
        Thread.CurrentThread.Abort(); // B
    }

    static async Task T()
    {
        try
        {
            await Abort();
        }
        catch
        {
            Console.WriteLine("catch");
            throw;
        }
        finally
        {
            Console.WriteLine("finally");
            await Task.Yield(); // C
        }
    }
}

When I compile this in Visual Studio 2015, the output

catch

But if I make any of these changes ...

  • Exclude row A (and remove the call Thread.ResetAbort()in Main-another oddity)
  • Change line B to throw new Exception();
  • Delete line C

then exit

catch
finally

, ( - )?

. ( ASP.NET) ThreadAbortException HttpResponse.Redirect, - finally.

+4

Source: https://habr.com/ru/post/1692059/


All Articles