I came across this definition of Object constructor (metadata from mscorlib.dll)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Object();
I didn’t understood what ConstrainedExecution (Cer.MayFail) mean can someone tell me with an example in this case.
I came across this code, also tell me if it is correct to write like this,
public class MyClass
{
private static object instanceLock = new object();
private void Func()
{
bool instanceLockTaken = false;
Monitor.TryEnter(instanceLock, ref instanceLockTaken);
//...
Monitor.Exit(instanceLock);
}
}
Constrained Execution is what you’re trying to achieve by locking the thread.
From: http://msdn.microsoft.com/en-us/magazine/cc163716.aspx
In your case, because the object is static and only created once, this will not be a problem.
Monitor.TryEnterreturns immediately even if a lock was not acquired. It has a boolean value, which you’re not checking, something like this would work:However, this code would mean that the
if {}block would not be executed every time, if you want to acquire a lock on every thread, you’ll need to do something like this:This means that only a single thread can run the contents of the
lock {}statement at a time, and the contents of the lock statement will be executed every time.On a side note, you can also make the object you’re locking
readonly:private static readonly object instanceLock = new object();