代码最终会在重定向后运行吗?

Shi*_*iji 8 c# asp.net

以下面的代码为例:

   try
   {
      Response.Redirect(someurl);
    }
    finally
    {
       // Will this code run?
    }
Run Code Online (Sandbox Code Playgroud)

finally块中的代码会运行吗?

Nei*_*oss 12

是.

试试看吧!

  • .....你很快就会发现你应该先教他如何游泳:) (5认同)

Cha*_*ion 6

简单到足以测试:

try
{
  Response.Redirect(someurl);
}
finally
{
   File.WriteAllText("C:\\Temp\\test.txt", "The finally block ran.");
}
Run Code Online (Sandbox Code Playgroud)


Phi*_*ert 6

它会运行.Response.Redirect实际上会抛出一个ThreadAbortException,这就是为什么之后的代码不能运行(当然,除了finally块中的任何东西).


Dav*_*and 5

确实会的。请参阅这篇 MSDN 文章: 最终总是执行