I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?
1)
void example() { lock (mutex) { //... } return myData; }
2)
void example() { lock (mutex) { //... return myData; } }
Which one should I use?
Essentially, which-ever makes the code simpler. Single point of exit is a nice ideal, but I wouldn’t bend the code out of shape just to achieve it… And if the alternative is declaring a local variable (outside the lock), initializing it (inside the lock) and then returning it (outside the lock), then I’d say that a simple ‘return foo’ inside the lock is a lot simpler.
To show the difference in IL, lets code:
(note that I’d happily argue that
ReturnInsideis a simpler/cleaner bit of C#)And look at the IL (release mode etc):
So at the IL level they are [give or take some names] identical (I learnt something ;-p). As such, the only sensible comparison is the (highly subjective) law of local coding style… I prefer
ReturnInsidefor simplicity, but I wouldn’t get excited about either.