Will code in finally run after a redirect?

后端 未结 10 1312
别跟我提以往
别跟我提以往 2021-01-02 11:08

Take for example the following code:

   try
   {
      Response.Redirect(someurl);
    }
    finally
    {
       // Will this code run?
    }
相关标签:
10条回答
  • 2021-01-02 12:00

    Yes. Code in the finally is guaranteed to run, unless something catastrophic happens.

    0 讨论(0)
  • 2021-01-02 12:05

    Yes. Here is how you can check if I am right or not. Simply place a message box or write something to the console from finally and you will have your answer.

    0 讨论(0)
  • 2021-01-02 12:10

    Simple enough to test:

    try
    {
      Response.Redirect(someurl);
    }
    finally
    {
       File.WriteAllText("C:\\Temp\\test.txt", "The finally block ran.");
    }
    
    0 讨论(0)
  • 2021-01-02 12:10

    The code in the finally will run, but it will run before the redirect, since the redirect won't be sent to the browser until the method returns, and the finally code will execute before the method returns.

    0 讨论(0)
提交回复
热议问题