internal bool TryAdd()

in rd-net/Lifetimes/Lifetimes/LifetimeDefinition.cs [597:633]


    internal bool TryAdd(object action)
    {
      CheckNotNull(action);
      
      //will never be terminated; need to be revised for debugging
      if (IsEternal)
        return true;

      using (var mutex = new UnderMutexCookie(this, LifetimeStatus.Canceling))
      {
        if (!mutex.Success)
          return false;

        var resources = myResources;
        if (Mode.IsAssertion) Assertion.AssertNotNull(resources, "{0}: `resources` can't be null under mutex while status < Terminating", this);
        
        if (myResCount == resources!.Length)
        {
          var countAfterCleaning = 0;
          for (var i = 0; i < myResCount; i++)
          {
            //can't clear Canceling because TryAdd works in Canceling state 
            if (resources[i] is LifetimeDefinition ld && ld.Status >= LifetimeStatus.Terminating)
              resources[i] = null;
            else
              resources[countAfterCleaning++] = resources[i];
          }

          myResCount = countAfterCleaning;
          if (countAfterCleaning * 2 > resources.Length)
            Array.Resize(ref myResources, countAfterCleaning * 2); //must be more than 1, so it always should be room for one more resource
        }

        myResources![myResCount++] = action;
        return true;
      }
    }