.net - Why do we need to lock and object in C#? -
this i've never understood. seems hack create dummy object gets lock
ed, example
class account { decimal balance; private object thislock = new object(); public void withdraw(decimal amount) { lock (thislock) { if (amount > balance) { throw new exception("insufficient funds"); } balance -= amount; } } }
from https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx.
why couldn't language designers make
class account { decimal balance; public void withdraw(decimal amount) { lock { if (amount > balance) { throw new exception("insufficient funds"); } balance -= amount; } } }
would equivalent?
the instance passed lock
serves identify critical section.
you may have number of unrelated critical sections in code, , each 1 locking different object. parameterless lock
statement likes of 1 suggest wouldn't able distinguish between many critical sections.
edit
although might seem obvious, it's worth noting every single part needing enter given critical section must have access locked object. it's not matter of creating arbitrary instance before , in same scope lock
statement.
Comments
Post a Comment