/// <summary> /// Tries to acqurie a lock on <paramref name="lockObj"/> and logs this occurens in to the logfile. /// </summary> /// <param name="lockObj">The lock object to wait for.</param> /// <param name="callerName">Caller member name. Automatically filled out by the compiler.</param> /// <returns>A <see cref="LockWithLog"/> object with reference to the lock object. Call <see cref="Dispose"/> to release the lock.</returns> /// <example> /// This example shows the intended usage of this method. /// <code> /// var locker = new LockObj("Name for the lock"); /// using(LockWithLog.Lock(locker)) /// { /// // Critical code /// } // Calls <see cref="Dispose"/> to release the lock. /// </code> /// </example> public static LockWithLog Lock(LockObj lockObj, [System.Runtime.CompilerServices.CallerMemberName] string callerName = "") { var lwl = new LockWithLog(lockObj, callerName); lwl._log.Debug($"{lwl._lockNumber} - Try to acquire lock {lockObj.Name}."); Monitor.Enter(lwl._lockObj); lwl._log.Debug($"{lwl._lockNumber} - Acquired lock {lockObj.Name}."); return(lwl); }
private LockWithLog(LockObj lockObj, string callerName) { if (lockObj == null) { throw new ArgumentNullException(nameof(lockObj)); } if (callerName == null) { throw new ArgumentNullException(nameof(callerName)); } _lockObj = lockObj; _callerName = callerName; _log = log4net.LogManager.GetLogger(callerName); lock (_lockNumberLock) { _lockNumber = _nextLogNumber; _nextLogNumber++; } }