How Console.WriteLine affects the exception stack

I have the following code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Started");
        var res = GetSlowStringAsync();

        res.ContinueWith(
            c =>
                {
                    Console.WriteLine("Will it crash?");
                    //Console.WriteLine(c.Result);
                }
            );

        //Console.WriteLine("Press any key");
        Console.ReadKey();
        Console.WriteLine("Continue on the main thread");

        GC.Collect();
        Console.WriteLine("Memory cleared");

        Thread.Sleep(10000);
    }

    public static async Task<string> GetSlowStringAsync()
    {
        await Task.Delay(2000);
        throw new Exception("will you handle it?");
        return "somestring";
    }
}

Also in App.config I added the following lines:

<runtime>
    <ThrowUnobservedTaskExceptions enabled ="true" />
</runtime>

I am using visual studio 2015 14.0.23107.0 D14REL Target .Net Framework 4.6. Run the command "Start without debugging".

If after the question “Will it crash” press any button, the program will work.

But if you uncomment

Console.WriteLine("Press any key");

as well as execute in the Run without debugging mode, then the program will not crash. Why does Console.WriteLine affect the way you get exceptions?

+4
source share
1 answer

, . , , Thread.Sleep() . , . , , .

, :

  • GC.Collect() garbage - res. ,
  • GC.Collect() main(). Console.WriteLine() TaskExceptionHolder. , .

: "" > "" > "" > "" > " JIT". , . res = null; GC.Collect() , , res Debug. GC.Collect() , .

, , , , , . Environment.HasShutdownStarted AppDomain.CurrentDomain.IsFinalizingForUnload TaskExceptionHolder finalizer. , , , , , . , Main() GC.Collect(), Console.WriteLine(), , .

GC.WaitForPendingFinalizers() . , :)

+3

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


All Articles