Home Why isn't ThreadAbortException automatically rethrown if raised after an asynchronous await?
Reply: 0

Why isn't ThreadAbortException automatically rethrown if raised after an asynchronous await?

user1667
1#
user1667 Published in April 24, 2018, 6:37 am

While investigating an issue with finally, await, and ThreadAbortException, I came another quirk. According to the documentation:

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

But consider this console program:

class Program
{
    static void Main()
    {
        Run(false).GetAwaiter().GetResult();
        Run(true).GetAwaiter().GetResult();
    }

    static async Task Run(bool yield)
    {
        Console.WriteLine(yield ? "With yielding" : "Without yielding");
        try
        {
            try { await Abort(yield); }
            catch (ThreadAbortException)
            {
                Console.WriteLine("    ThreadAbortException caught");
            } // <-- ThreadAbortException should be automatically rethrown here
        }
        catch (ThreadAbortException)
        {
            Console.WriteLine("    Rethrown ThreadAbortException caught");
            Thread.ResetAbort();
        }
    }

    static async Task Abort(bool yield)
    {
        if (yield)
            await Task.Yield();
        Thread.CurrentThread.Abort();
    }
}

When I compile this in Visual Studio 2015, the output is:

Without yielding
    ThreadAbortException caught
    Rethrown ThreadAbortException caught
With yielding
    ThreadAbortException caught

So a ThreadAbortException raised after Task.Yield() is no longer automatically rethrown by a catch block! Why is this?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.325144 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO