在C# 6中出现了异常过滤器。因此,我们可以编写一些重试逻辑,例如:
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);
}
在控制台应用程序中它运行得很好。 但是,如果我们创建一个带有“优化代码”选项的网站应用程序,会出现无限循环,因为“i”的值永远不会改变。如果没有“优化代码”,这将按预期工作。 如何测试: 在空的asp.net网站应用程序中创建(我尝试了.net 4.5.2和.net 4.6)。将此代码添加到全局应用程序类
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);
}
}
项目属性 -> 构建 -> 勾选“优化代码”。运行应用程序。得到无限循环。
这是正确的行为还是编译器中的错误?请注意,不要删除 HTML 标签。
更新1:似乎是一种非常罕见的情况,与单个递减和重新抛出异常有关。在 Windows 7 上使用 VS 2015 编译时会重现此问题(尝试在几台计算机上进行操作)。但在 Windows 10 上使用 VS2015 就没有问题。
如果将代码更改如下,则也可以正常工作。
int i = 3;
do
{
try
{
throw new Exception();
}
catch (Exception) when (--i > 0)
{
Thread.Sleep(10);
}
} while (true);
哪个在实际应用中更合适(因为堆栈展开)