简体   繁体   中英

Lock in Framework 3.5 vs 4.0?

AFAIK , there is a difference between lock in those 2 versions.

Framework 4 added one more check if there was an exception during monitor enter ( like out of memory exception)

And there is a lockTaken flag which indicates if a lock should be released (in a finally clause) or not ( due to fail code in a try clause).

Something like

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

(very much similar to the using code (dispose...))

But viewing by relfector I see totally different thing :

[SecuritySafeCritical]
public static void Enter(object obj, ref bool lockTaken)
{
    if (lockTaken)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_MustBeFalse"), "lockTaken");
    }
    ReliableEnter(obj, ref lockTaken);
}

where is the pattern of try , finally ?

What am I missing ?

You should take a look at decompiled method that uses lock statement instead of looking into framework's code. So, if you'll try to decompile following method:

object syncRoot = new object();
void Foo()
{
  lock(syncRoot) {}
}

You'll see what you're expected:

void Foo()
{
  bool lockTaken;
  try
  {
    Monitor.Enter(syncRoot, out lockTaken);
  }
  finally
  {
    if (lockTaken)
        Monitor.Exit(syncRoot);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM