Why is TaskCanceledException thrown and does not always breaks into the debugger

后端 未结 3 1819
孤独总比滥情好
孤独总比滥情好 2020-12-11 07:17

I\'m digging into the async-await mechanism and observed the throwing of a TaskCanceledException that I can\'t explain yet.

In the sample b

3条回答
  •  轮回少年
    2020-12-11 08:11

    If you replace the Func with a method, it passes.

        private static async Task TestNullCase()
        {
            // This does not throw a TaskCanceledException
            await Task.Run(() => 5);
    
            // This does throw a TaskCanceledException
            await Task.Run(() => GetNull());
        }
    
        private static object GetNull()
        {
            return null;
        }
    

    UPDATE

    After letting ReSharper convert both lambdas to variables:

        private static async Task TestNullCase()
        {
            // This does not throw a TaskCanceledException
            Func func = () => 5;
            await Task.Run(func);
    
            // This does throw a TaskCanceledException
            Func function = () => null;
            await Task.Run(function);
        }
    

    So, the second form is incorrectly interpreted as Func instead of your intent, which I believe is Func. And because the Task passed in is null, and because you can't execute a null, you get a TaskCanceledException. If you change the variable type to Func it works without any additional changes.

    提交回复
    热议问题