2009-10-23 26 views
3

在.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之前的最後一個版本中存在異步異常,會發生什麼情況?

答:ThreadAbortException

當此異常升高時, 運行結束線程之前執行所有的最終 塊。

+2

如果在monitor.exit之前的最終權限中存在異步異常,會發生什麼情況? – 2010-01-28 11:27:00

+0

我不知道其他異步異常,但是CLR可以防止終止異常終止中斷塊 - 而且其他異步異常更有可能使流程崩潰。 – 2010-03-05 11:26:01

回答

5

當你在問題的最後建議權,問題在於,asynchronous exception可以在撥號後進入try塊之前拋給Monitor.Enter不過。

新的做事方式可以確保無論發生什麼事情,您都會打到finally塊,並能夠釋放鎖如果您獲得了。 (例如,如果Monitor.Enter引發異常,您可能無法獲得它。)

IIRC,這是針對.NET 4.0時lock關鍵字的新行爲。

+1

是的,鎖已更改爲使用新的構造(或至少它在beta1) – 2009-10-23 09:56:29

+1

如果您可以回答Eamon Nerbonne問題,我會接受答案;) – Guillaume 2010-03-05 11:06:24