File tree Expand file tree Collapse file tree 4 files changed +54
-2
lines changed Expand file tree Collapse file tree 4 files changed +54
-2
lines changed Original file line number Diff line number Diff line change @@ -18,8 +18,11 @@ public override T Create()
1818 /// <inheritdoc />
1919 public override bool Return ( T obj )
2020 {
21- // DefaultObjectPool<T> doesn't call 'Return' for the default policy.
22- // So take care adding any logic to this method, as it might require changes elsewhere.
21+ if ( obj is IResettable resettable )
22+ {
23+ return resettable . TryReset ( ) ;
24+ }
25+
2326 return true ;
2427 }
2528}
Original file line number Diff line number Diff line change 1+ // Licensed to the .NET Foundation under one or more agreements.
2+ // The .NET Foundation licenses this file to you under the MIT license.
3+
4+ namespace Microsoft . Extensions . ObjectPool ;
5+
6+ /// <summary>
7+ /// Defines a method to reset an object to its initial state.
8+ /// </summary>
9+ public interface IResettable
10+ {
11+ /// <summary>
12+ /// Reset the object to a neutral state, semantically similar to when the object was first constructed.
13+ /// </summary>
14+ /// <returns><see langword="true" /> if the object was able to reset itself, otherwise <see langword="false" />.</returns>
15+ /// <remarks>
16+ /// In general, this method is not expected to be thread-safe.
17+ /// </remarks>
18+ bool TryReset ( ) ;
19+ }
Original file line number Diff line number Diff line change 11#nullable enable
2+ Microsoft.Extensions.ObjectPool.IResettable
3+ Microsoft.Extensions.ObjectPool.IResettable.TryReset() -> bool
Original file line number Diff line number Diff line change @@ -69,6 +69,34 @@ public void DefaultObjectPool_Return_RejectedByPolicy()
6969 Assert . NotSame ( list1 , list2 ) ;
7070 }
7171
72+ [ Fact ]
73+ public static void DefaultObjectPool_Honors_IResettable ( )
74+ {
75+ var p = new DefaultObjectPool < Resettable > ( new DefaultPooledObjectPolicy < Resettable > ( ) ) ;
76+ var r = new Resettable ( ) ;
77+
78+ r . ResetReturnValue = false ;
79+ p . Return ( r ) ;
80+ Assert . Equal ( 1 , r . ResetCallCount ) ;
81+ Assert . NotSame ( r , p . Get ( ) ) ;
82+
83+ r . ResetReturnValue = true ;
84+ p . Return ( r ) ;
85+ Assert . Equal ( 2 , r . ResetCallCount ) ;
86+ Assert . Same ( r , p . Get ( ) ) ;
87+ }
88+
89+ private sealed class Resettable : IResettable
90+ {
91+ public int ResetCallCount { get ; set ; }
92+ public bool ResetReturnValue { get ; set ; }
93+ public bool TryReset ( )
94+ {
95+ ResetCallCount ++ ;
96+ return ResetReturnValue ;
97+ }
98+ }
99+
72100 private class ListPolicy : IPooledObjectPolicy < List < int > >
73101 {
74102 public List < int > Create ( )
You can’t perform that action at this time.
0 commit comments