private void acquireLock(string vehicleCode) { var lockDoc = new VehicleLock(vehicleCode); var lockAcquired = false; var attempts = 0; while (!lockAcquired && attempts < this.NumberOfRetries) { try { this.vehicleLocksCollection.InsertOne(lockDoc); lockAcquired = true; } catch { attempts++; if (attempts < this.NumberOfRetries) { log.Warn($"Cannot acquire lock for vehicle { vehicleCode }. Attempt #{ attempts } of { this.NumberOfRetries }."); } else { log.Error($"Cannot acquire lock for vehicle { vehicleCode }. Giving up on insertion after { this.NumberOfRetries } attempts."); throw; } Thread.Sleep(this.RetriesInterval_msec); } } }
private void acquireLock(string vehicleCode) { var lockDoc = new VehicleLock(vehicleCode); var lockAcquired = false; var attempts = 0; while (!lockAcquired && attempts < this.NumberOfRetries) { try { this.vehicleLocksCollection.InsertOne(lockDoc); lockAcquired = true; } catch { attempts++; // compute some jitter in order to prevent thread synchronization int retryInterval = computeRetryIntervalWithJitter(this.RetriesInterval_msec); if (attempts < this.NumberOfRetries) { log.Info($"Cannot acquire lock for vehicle { vehicleCode }. Attempt #{ attempts } of { this.NumberOfRetries }. Waiting for { retryInterval } before retry."); } else { log.Error($"Cannot acquire lock for vehicle { vehicleCode }. Giving up on insertion after { this.NumberOfRetries } attempts."); throw; } Thread.Sleep(retryInterval); } } }