在.NET4,Monitor.Enter(Object)被標記爲過時:.NET4,Monitor.Enter(lockObject,acquiredLock)
[ObsoleteAttribute("This method does not allow its caller to reliably release the lock. Please use an overload with a lockTaken argument instead.")]
public static void Enter(
Object obj
)
而且還有一個新方法Monitor.Enter(lockObject, acquiredLock)用這種用法:
bool acquiredLock = false;
try
{
Monitor.Enter(lockObject, ref acquiredLock);
// Code that accesses resources that are protected by the lock.
}
finally
{
if (acquiredLock)
{
Monitor.Exit(lockObject);
}
}
我用於這樣做:
Monitor.Enter(lockObject);
try
{
// Code that accesses resources that are protected by the lock.
}
finally
{
Monitor.Exit(lockObject);
}
是不是錯了?爲什麼? 也許在進入之後但在嘗試之前進行中斷?
正如Eamon Nerbonne所問:如果在monitor.exit之前的最後一個版本中存在異步異常,會發生什麼情況?
當此異常升高時, 運行結束線程之前執行所有的最終 塊。
如果在monitor.exit之前的最終權限中存在異步異常,會發生什麼情況? – 2010-01-28 11:27:00
我不知道其他異步異常,但是CLR可以防止終止異常終止中斷塊 - 而且其他異步異常更有可能使流程崩潰。 – 2010-03-05 11:26:01