In C# 6 appears exception filters. So we can write some retry 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);
}
In console app it works great. But if we create website app with "optimize code" there will be infinite loop, because value of 'i' never changes. Without "optimize code" this worked as expected. How to test: Create in empty asp.net website application (i try .net 4.5.2 and .net 4.6). add this code to 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". Run application. Get Infinite loop. Is this right behaivior or it'a bug in compiller?
Upd1:
So it's seems very rare condition with unar decrement and rethrowing exception.
repeated while compile in VS 2015 on windows 7 (try it on several machines). In VS2015 on windows 10 works fine.
Also it's work if change code like this
int i = 3;
do
{
try
{
throw new Exception();
}
catch (Exception) when (--i > 0)
{
Thread.Sleep(10);
}
} while (true);
which will be more suitable in real world example (because unwinded stack)