How to write correctly when an operation requires both at the same time?

try { lock(locker) { .... } } catch(...) { ... } 

or so

 lock(locker) { try { ... } catch(...) { ... } } 

And how to be in case of an exception, if it is locked?

  • and so, and so it is possible. "exceptions ... will be locked" - what is it like? - Igor
  • @Igor, that is, if an error has occurred in the operation, then somehow it will be necessary to remove the lock, because of the error it will remain active, as I understand it. - Bulson
  • @Bulson why? - Pavel Mayorov
  • Read in any tutorial that the lock construct does ... - Pavel Mayorov
  • 3
    No, it will not. lock is the abbreviated entry of Monitor.Enter/Exit with try-finaly . msdn.microsoft.com/en-us/library/c5kehkcz.aspx - Igor

1 answer 1

On SO, it is strongly not recommended to use try-catch with lock . And advised to do so:

 lock(whatever) { try { MakeAMess(); } finally { CleanItUp(); // Либо доводим операцию до конца, либо откатываем в прежнее состояние } } 

They write that throwing an exception into lock breaks the essence for which this lock exists. Therefore, if an exception occurred, there are two options:

  1. Beat the process completely with Environment.FailFast()
  2. Or, if possible, roll back to the previous state, before lock .

The original can be found here .