public ObjectPool(Func <ObjectPool <T>, T> createFunc, Action <T> resetAction = null, int initialBufferSize = 0, PoolResetMode resetMode = PoolResetMode.AfterUse, int dropTimeFrequencyInSeconds = 60, Action <T> dropAction = null) { _objectStack = new ConcurrentStack <T>(); _createFunc = createFunc; _resetAction = resetAction; _resetMode = resetMode; if (initialBufferSize > 0) { Preallocate(initialBufferSize); } if (dropTimeFrequencyInSeconds > 0) { var cancellationTokenSource = new CancellationTokenSource(); dropTimeFrequencyInSeconds = dropTimeFrequencyInSeconds * 1000; var token = cancellationTokenSource.Token; Task.Delay(dropTimeFrequencyInSeconds, token).ContinueWith(async tsk => { while (!token.IsCancellationRequested) { var count = _objectStack.Count; if (count > 2 && _objectStack.TryPop(out var item)) { dropAction?.Invoke(item); } await Task.Delay(dropTimeFrequencyInSeconds, token).ConfigureAwait(false); } }, token); } }
public ReferencePool(int initialBufferSize = 0, Action <T> resetAction = null, Action <T> onetimeInitAction = null, PoolResetMode resetMode = PoolResetMode.AfterUse, int dropTimeFrequencyInSeconds = 120, Action <T> dropAction = null, int dropMaxSizeThreashold = 15) { _objectStack = new ConcurrentStack <T>(); _resetAction = resetAction; _onetimeInitAction = onetimeInitAction; _resetMode = resetMode; _dropAction = dropAction; _dropmaxsizeThreshold = dropMaxSizeThreashold; if (_dropmaxsizeThreshold < initialBufferSize) { _dropmaxsizeThreshold = initialBufferSize; } if (initialBufferSize > 0) { Preallocate(initialBufferSize); } if (dropTimeFrequencyInSeconds > 0 && _dropAction != null) { var frequency = TimeSpan.FromSeconds(dropTimeFrequencyInSeconds); _dropTimer = new Timer(DropTimerMethod, this, frequency, frequency); } }