Monthly Archives: June 2012

Finally Definitely Executes Last

Finally executes last, every time, right? I recently came across a scenario that made me second-guess myself, and I had to throw together a quick sample project to be certain my understanding was correct.

For example:

private readonly object sync = new object();

private int GetSomeValue()
{
	Monitor.Enter(sync);
	try
	{
		return GetTheValue();
	}
	finally
	{
		Monitor.Exit(sync);
	}
}

private int GetTheValue()
{
	return 42;
}

Sure, the code in the finally block will execute no matter what, so I am confident that the lock will be released. But, what about that return statement inside the try? Is there any funny business going on there? If there is, it might defeat the purpose of employing a lock.

So to be sure, I tossed in a breakpoint inside the GetTheValue() method, and another inside the finally. I want to be sure that the GetTheValue() method executes before the lock is released. And, sure enough, it does.