public bool TryAdd(TResource resource) { var taskCompletionSource = new TaskCompletionSource <bool>(); var request = new AddResourceMessage(resource, taskCompletionSource); if (!_messageHandler.Post(request)) { taskCompletionSource.SetException(GetObjectDisposedException()); } // We can wait synchronously for the Task Result because RemoveResourceRequestMessage // will always be handled immediately by the ActionBlock. return(taskCompletionSource.Task.Result); }
private void HandleAddResource(AddResourceMessage addResourceMessage) { // Only add the resource if we didn't already exceed the maximum var success = _availableResources.Count < _maxNumResources; if (success) { var resource = addResourceMessage.Resource; var timestampedResource = TimestampedResource.Create(resource); _availableResources.Enqueue(timestampedResource); } addResourceMessage.ResultTaskCompletionSource.SetResult(success); }