1.

What Is The Difference Between Monitor.enter And Monitor.exit?

Answer»

C#’s LOCK statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with a try/finally block. Here’s (a simplified VERSION of) what’s actually happening WITHIN the Go METHOD of the preceding

example:

Monitor.Enter (_locker);

try

{

if (_val2 != 0) Console.WriteLine (_val1 / _val2);

_val2 = 0;

}

finally { Monitor.Exit (_locker); }

Calling Monitor.Exit without first calling Monitor.Enter on the same object throws an EXCEPTION.

C#’s lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with a try/finally block. Here’s (a simplified version of) what’s actually happening within the Go method of the preceding

example:

Monitor.Enter (_locker);

try

{

if (_val2 != 0) Console.WriteLine (_val1 / _val2);

_val2 = 0;

}

finally { Monitor.Exit (_locker); }

Calling Monitor.Exit without first calling Monitor.Enter on the same object throws an exception.



Discussion

No Comment Found