How does compiller optimize exception filters in C #?

Exeption filters appear in C # 6. Thus, we can write repeat logic as

public static void Retry()
    {
        int i = 3;
        do
        {
            try
            {
                throw new Exception();
            }
            catch (Exception) when (--i < 0)
            {
                throw;
            }
            catch (Exception)
            {
                Thread.Sleep(10);
            }
        } while (true);
    }

It works great in a console application. But if we create a web application with "code optimization", there will be an endless loop, because the value of "i" will never change. Without "code optimization," this worked as expected. How to check: Create an asp.net website in a blank application (I'm trying .net 4.5.2 and .net 4.6). add this code to the global application class

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        int i = 3;
        do
        {
            try
            {
                throw new Exception();
            }
            catch (Exception) when (--i < 0)
            {
                throw;
            }
            catch (Exception)
            {
                Thread.Sleep(10);
            }
        } while (true);
    }
}

Project Properties -> Build -> check "optimize code". Launch the application. Get an endless loop. Is this the correct behavior or is it a compiler error?

Upd1: , , . VS 2015 Windows 7 ( ). VS2015 10 .
, ,

int i = 3;
   do
   {
       try
       {
          throw new Exception();
       }
       catch (Exception) when (--i > 0)
       {
          Thread.Sleep(10);
       }
   } while (true);

( )

+4
2

, . , . , .

-, . , . CQS; - , .

-, . - , , ( , ), catch? .

:

int i = 3;
do
{
  try
  {
    throw new Exception();
  }
  catch (Exception)
  {
    if (--i < 0)
      throw;
    Thread.Sleep(10);
  }
} while (true);

, , -, . , , , , .

+2

. catch. 1.

public static void Retry()
{
    int i = 3 - 1;
    do
    {
        try
        {
            throw new Exception();
        }
        catch (Exception) when (i < 0)
        {
            throw;
        }
        catch (Exception)
        {
            i--;
            Thread.Sleep(10);
        }
    } while (true);
}

Ok. , . , 32- . 64- .

0

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


All Articles