3

The code below causes a code analysis warning CA2000, claiming that I need to dispose of getRequest along all code paths before it goes out of scope. Tweaking the code slightly, for example removing the when from the catch, eliminates the warning.

try
{
    using (var getRequest = new HttpRequestMessage(HttpMethod.Get, uri))
    {
        using (var result = client.SendAsync(getRequest).Result)
        {
        }
    }
}
catch (AggregateException exc) when (exc.InnerExceptions.Count >= 0)
{
}

On which code path is dispose not called, and why does catch/when affect things?

Note: I'm using VS2015's built in code analysis. CA2000 is in the managed binary analysis ruleset, and is (for me) unchecked by default for new solutions. (VS2017 also emits the same warnings)

Rob
  • 4,327
  • 6
  • 29
  • 55
  • I took this hunk of code and popped it in an empty console app (added various local variables to make it compile) and click Analyse code in VS 2017 and it came up with nothing. What code analyser are you using? – Dave Sep 26 '18 at 14:55
  • I have enabled it, pasted your code and also don't get any error. Which framework are we talking about? Legacy or .NET Core? – Jakub Szumiato Sep 26 '18 at 15:35
  • I was able to reproduce the issue. It occurs in the debug build but not the release build. Still digging into the IL a bit to try to find out why... – Dark Falcon Sep 26 '18 at 15:40
  • @Rob yeah got it reproduced now – Dave Sep 26 '18 at 15:45
  • For people coming along who don't want to have to type everything into VS here is a link to the ILSpy decompiled C# code https://www.pastiebin.com/5babac6311371 and the ILSpy decompiled IL code: https://www.pastiebin.com/5babaceb7fd50 – Dave Sep 26 '18 at 16:01
  • 1
    Slightly simpler code with the same problem: https://www.pastiebin.com/5babafcb1ddce – Dark Falcon Sep 26 '18 at 16:12

0 Answers0