Finally block is executed only on Debug mode

筅森魡賤 提交于 2019-12-12 01:16:00

问题


Question is taken from here: SO - Timeout in c# tests

I created a simple unit test like this:

[Timeout(1000)][TestMethod]
public void TestMethod1()
{
    try
    {
        System.Threading.Thread.Sleep(2000);
    }
    finally
    {
        Console.WriteLine("Executed");
    }
}

When I run the test, the finally block is not executed. But when I debug it, it does. Why is this happening?


回答1:


You specify the test timeout at 1000 ms, while your method sleeps for 2000 ms. This results in your test method being prematurely force-closed by the test framework, so it doesn't leave the Sleep call and doesn't have time to reach finally block. Debugging probably disables the timeout attribute.




回答2:


The Timeout attribute simply does not apply to Debugging sessions.




回答3:


Timeout is disabled during debugging, so you get to see Console.WriteLine() output.

But i still think finally is executed in vs2010. If you try to show a message box System.Windows.Forms.MessageBox.Show("finally") you should be able to see it pops up.

Console.WriteLine output is lost after timeout in vs2010.



来源:https://stackoverflow.com/questions/13515082/finally-block-is-executed-only-on-debug-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!