Call Monitor.Enter inside the try statement and call it outside the try statement

a. In what cases does this code fail:

try { Monitor.Enter(someObj); //Do something important } finally { Monitor.Exit(someObj); } 

And this code is not interrupted:

 Monitor.Enter(someObj); try { //Do something important } finally { Monitor.Exit(someObj); } 

b. Which one do you use when you are not completing a critical section with a statement

thanks

+4
source share
1 answer

Well, lock(someObj) will be simpler and will use the new Monitor overloads in .NET 4 when used.

In .NET 4, the following is preferred (emph: lock will do this for you ):

 bool lockTaken = false; try { Monitor.Enter(lockObj, ref lockTaken); // do something important } finally { if (lockTaken) Monitor.Exit(lockObj); } 

Why see Eric Lippert's blog

But the rest: the second; otherwise, if the Enter call fails ( any method call may fail), then try Exit and the blocked one, which you do not have.

+5
source

Source: https://habr.com/ru/post/1333037/


All Articles