2017-06-29 1 views
0

Ich Fehlerbehebung alten Quellcode und stieß auf eine Anweisung wie folgt:C# Monitor.Exit in Try/Catch

if (Monitor.TryEnter(lockObj)) 
{ 
    try 
    { 
     //does something 
     if (failing_condition) 
     { 
      Monitor.Exit(lockObj); 
      throw new Exception("Oops!"); 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
     finally 
     { 
      Monitor.Exit(lockObj); 
     } 
    } 
} 

Der Code wird mit einem Gibt es einen sicheren Weg System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code.

Absturz zu Rufen Sie Monitor.Exit() auf der fehlerhaften Bedingung und wenn die normale Ausführung beendet ist?

Antwort

6

Tun Sie es einfach im finally-Block, es läuft immer, auch wenn oben eine Ausnahme ausgelöst wird. Auch der Fangabschnitt ist nicht notwendig.

if(Monitor.TryEnter(lockObj)) { 
    try { 
    //does something 
    if(failing_condition) {  
     throw new Exception("Oops!"); 
    } 
    } 
    finally { 
    Monitor.Exit(lockObj); 
    } 
} 
+0

'catch' Block in diesem Fall überschreibt die Ausnahmedetails, die hier gemeint sein können. – VMAtm

Verwandte Themen