-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions
Milestone
Description
Background and motivation
We use a lot of object pools in our environment and its clumsy to have to implement dedicated policy types when we generally want a single behavior applied to a large variety of object types. We adopted a solution of having all these objects declare themselves as IResettable and then a single policy suffices to deal with these objects
API Proposal
namespace Microsoft.Extensions.ObjectPool;
/// <summary>
/// Defines a method to reset an object to its initial state.
/// </summary>
public interface IResettable
{
/// <summary>
/// Reset the object to a neutral state, semantically similar to when the object was first constructed.
/// </summary>
/// <remarks>
/// In general, this method is not expected to be thread-safe.
/// </remarks>
void Reset();
}
/// <summary>
/// An object pool policy for resettable objects.
/// </summary>
public sealed class ResettablePooledObjectPolicy<T> : PooledObjectPolicy<T>
where T : notnull, IResettable, new()
{
public static ResettablePooledObjectPolicy<T> Instance { get; } = new();
private ResettablePooledObjectPolicy()
{
}
public override T Create() => new();
public override bool Return(T obj)
{
obj.Reset();
return true;
}
}API Usage
// a resettable object is one that logically can come back to its initial state
internal class MyState : IResettable
{
private readonly List<int> _data = new();
public void Add(int value) { _data.Add(value); }
public void Reset() { _data.Clear(); }
}
var pool = ObjectPool.Create<MyState>(ResettableObjectPoolPolicy<MyState>.Instance);
// or alternatively, there could be a new method on ObjectPool, which requires less typing...
var pool = ObjectPool.CreateResettable<MyState>();Alternative Designs
No response
Risks
No response
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions