- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoolFactory.cs
More file actions
Latest commit
286 lines (267 loc) · 19 KB
/
Copy pathPoolFactory.cs
File metadata and controls
286 lines (267 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
* Copyright 2017 Stanislav Muhametsin. All rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
usingResourcePooling.Async.Abstractions;
usingResourcePooling.Async.Implementation;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingUtilPack;
namespaceResourcePooling.Async.Implementation
{
/// <summary>
/// This delegate can be used to customize what exactly happens when taking the resource from <see cref="AsyncResourcePool{TResource}"/> which caches resources.
/// </summary>
/// <typeparam name="TInstance">The type of objects stored in <see cref="LocklessInstancePoolForClassesNoHeapAllocations{TInstance}"/> used by <see cref="AsyncResourcePool{TResource}"/>.</typeparam>
/// <param name="pool">The <see cref="LocklessInstancePoolForClassesNoHeapAllocations{TInstance}"/> pool where to acquire the instance.</param>
/// <param name="token">The cancellation token to use.</param>
/// <returns>Potentially asynchronously returns instance from <paramref name="pool"/>.</returns>
publicdelegateValueTask<TInstance>TakeFromInstancePoolDelegate<TInstance>(LocklessInstancePoolForClassesNoHeapAllocations<TInstance>pool,CancellationTokentoken)
whereTInstance:class,InstanceWithNextInfo<TInstance>;
/// <summary>
/// This delegate can be used to cusomize what exactly happens when returning the resource to <see cref="AsyncResourcePool{TResource}"/> which caches instances.
/// </summary>
/// <typeparam name="TInstance">The type of objects stored in <see cref="LocklessInstancePoolForClassesNoHeapAllocations{TInstance}"/> used by <see cref="AsyncResourcePool{TResource}"/>.</typeparam>
/// <param name="pool">The <see cref="LocklessInstancePoolForClassesNoHeapAllocations{TInstance}"/> pool where to acquire the instance.</param>
/// <param name="token">The cancellation token to use.</param>
/// <param name="instance">The instance to return to <paramref name="pool"/>.</param>
/// <returns>Potentially asynchronously returns value indicating whether <paramref name="instance"/> was returned to <paramref name="pool"/>.</returns>
publicdelegateValueTask<Boolean>ReturnToInstancePoolDelegate<TInstance>(LocklessInstancePoolForClassesNoHeapAllocations<TInstance>pool,CancellationTokentoken,TInstanceinstance)
whereTInstance:class,InstanceWithNextInfo<TInstance>;
internalsealedclassPoolLimitState
{
privateconstInt32DEFAULT_TICK=100;
privateInt32currentlyUsedUpResources;
privatereadonlyFunc<Int32>maxGetter;
privatereadonlyTimeSpantick;
publicPoolLimitState(
Func<Int32>getMaximumConcurrentlyUsedResources,
Int32waitTick=DEFAULT_TICK
)
{
this.maxGetter=ArgumentValidator.ValidateNotNull(nameof(getMaximumConcurrentlyUsedResources),getMaximumConcurrentlyUsedResources);
this.tick=TimeSpan.FromTicks(Math.Max(waitTick,DEFAULT_TICK));
}
internalasyncValueTask<TInstance>GetFromPoolLimited<TInstance>(
LocklessInstancePoolForClassesNoHeapAllocations<TInstance>pool,
CancellationTokentoken
)
whereTInstance:class,InstanceWithNextInfo<TInstance>
{
TInstanceinstance=null;
varacquired=false;
do
{
varseenMax=this.maxGetter();
varseenCurrent=this.currentlyUsedUpResources;
if(seenCurrent>=seenMax)
{
await
#if NET40
TaskEx
#else
Task
#endif
.Delay(this.tick,token);
}
elseif(Interlocked.CompareExchange(refthis.currentlyUsedUpResources,seenCurrent+1,seenCurrent)==seenCurrent)
{
acquired=true;
instance=pool.TakeInstance();
}
}while(!acquired&&!token.IsCancellationRequested);
returninstance;
}
internalValueTask<Boolean>ReturnToPoolLimited<TInstance>(
LocklessInstancePoolForClassesNoHeapAllocations<TInstance>pool,
CancellationTokentoken,
TInstanceinstance
)
whereTInstance:class,InstanceWithNextInfo<TInstance>
{
varretVal=instance!=null;
if(retVal)
{
try
{
pool?.ReturnInstance(instance);
}
finally
{
Interlocked.Decrement(refthis.currentlyUsedUpResources);
}
}
returnnewValueTask<Boolean>(retVal);
}
}
}
publicstaticpartialclassE_ResourcePooling
{
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource}"/> which will always create new instance of resource when acquiring resource from <see cref="AsyncResourcePool{TResource}"/>.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
publicstaticAsyncResourcePoolObservable<TResource>CreateOneTimeUseResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory
)=>newOneTimeUseAsyncResourcePool<TResource,AsyncResourceAcquireInfo<TResource>>(
ArgumentValidator.ValidateNotNullReference(factory),
instance =>instance,
acquireInfo =>acquireInfo
);
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource, TCleanUpParameter}"/> which will cache the resources it manages, but will not have upper bound on how many resources it caches. By calling <see cref="AsyncResourcePoolCleanUp{TCleanUpParameter}.CleanUpAsync"/> method it will close all resources which have been opened for too long.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource, TCleanUp}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
publicstaticAsyncResourcePoolObservable<TResource,TimeSpan>CreateTimeoutingResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory
)=>factory.CreateGenericTimeoutingResourcePool(null,null);
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource}"/> which will create up to given dynamic maximum of resources when acquiring them from <see cref="AsyncResourcePool{TResource}"/>.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <param name="getMaximumConcurrentlyUsedResources">The callback to get maximum amount of resources that can be concurrently in use.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="getMaximumConcurrentlyUsedResources"/> is <c>null</c>.</exception>
publicstaticAsyncResourcePoolObservable<TResource>CreateLimitedResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory,
Func<Int32>getMaximumConcurrentlyUsedResources
)
{
ArgumentValidator.ValidateNotNullReference(factory);
varstate=newPoolLimitState(getMaximumConcurrentlyUsedResources);
returnfactory.CreateGenericCachingResourcePool(
state.GetFromPoolLimited,
state.ReturnToPoolLimited
);
}
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource, TCleanUpParameter}"/> which will cache the resources it manages, and also will have a dynamic upper bound on how many resources it caches. By calling <see cref="AsyncResourcePoolCleanUp{TCleanUpParameter}.CleanUpAsync"/> method it will close all resources which have been opened for too long.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <param name="getMaximumConcurrentlyUsedResources">The callback to get maximum amount of resources that can be concurrently in use.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource, TCleanUp}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="getMaximumConcurrentlyUsedResources"/> is <c>null</c>.</exception>
publicstaticAsyncResourcePoolObservable<TResource,TimeSpan>CreateTimeoutingAndLimitedResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory,
Func<Int32>getMaximumConcurrentlyUsedResources
)
{
ArgumentValidator.ValidateNotNullReference(factory);
varstate=newPoolLimitState(getMaximumConcurrentlyUsedResources);
returnfactory.CreateGenericTimeoutingResourcePool(
state.GetFromPoolLimited,
state.ReturnToPoolLimited
);
}
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource}"/> which will create up to given static maximum of resources when acquiring them from <see cref="AsyncResourcePool{TResource}"/>.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <param name="maximumConcurrentlyUsedResources">The static integer indicating the maximum amount of resources that can be concurrently in use.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
publicstaticAsyncResourcePoolObservable<TResource>CreateLimitedResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory,
Int32maximumConcurrentlyUsedResources
)=>factory.CreateLimitedResourcePool(()=>maximumConcurrentlyUsedResources);
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource, TCleanUpParameter}"/> which will cache the resources it manages, and also will have a static upper bound on how many resources it caches. By calling <see cref="AsyncResourcePoolCleanUp{TCleanUpParameter}.CleanUpAsync"/> method it will close all resources which have been opened for too long.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <param name="maximumConcurrentlyUsedResources">The static integer indicating the maximum amount of resources that can be concurrently in use.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource, TCleanUp}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
publicstaticAsyncResourcePoolObservable<TResource,TimeSpan>CreateTimeoutingAndLimitedResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory,
Int32maximumConcurrentlyUsedResources
)=>factory.CreateTimeoutingAndLimitedResourcePool(()=>maximumConcurrentlyUsedResources);
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource}"/> which will call given callbacks when acquiring and returning resources of the <see cref="AsyncResourcePool{TResource}"/>.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <param name="takeFromPool">The callback to call when taking the resource from the pool.</param>
/// <param name="returnToPool">The callback to call when resource to the pool.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
/// <seealso cref="TakeFromInstancePoolDelegate{TInstance}"/>
/// <seealso cref="ReturnToInstancePoolDelegate{TInstance}"/>
publicstaticAsyncResourcePoolObservable<TResource>CreateGenericCachingResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory,
TakeFromInstancePoolDelegate<InstanceHolder<AsyncResourceAcquireInfo<TResource>>>takeFromPool,
ReturnToInstancePoolDelegate<InstanceHolder<AsyncResourceAcquireInfo<TResource>>>returnToPool
)=>newCachingAsyncResourcePool<TResource,InstanceHolder<AsyncResourceAcquireInfo<TResource>>>(
ArgumentValidator.ValidateNotNullReference(factory),
holder =>holder.Instance,
info =>newInstanceHolder<AsyncResourceAcquireInfo<TResource>>(info),
takeFromPool,
returnToPool
);
/// <summary>
/// Binds the given creation parameters and creates a <see cref="AsyncResourcePoolObservable{TResource, TCleanUp}"/> which will cache the resources, and call given callbacks when acquiring and returning resources of the <see cref="AsyncResourcePool{TResource}"/>. By calling <see cref="AsyncResourcePoolCleanUp{TCleanUpParameter}.CleanUpAsync"/> method it will close all resources which have been opened for too long.
/// </summary>
/// <typeparam name="TResource">The type of resource.</typeparam>
/// <param name="factory">This <see cref="AsyncResourceFactory{TResource}"/>.</param>
/// <param name="takeFromPool">The callback to call when taking the resource from the pool.</param>
/// <param name="returnToPool">The callback to call when resource to the pool.</param>
/// <returns>An <see cref="AsyncResourcePoolObservable{TResource, TCleanUp}"/> using this <see cref="AsyncResourceFactory{TResource}"/> to create new resources.</returns>
/// <exception cref="NullReferenceException">If this <see cref="AsyncResourceFactory{TResource}"/> is <c>null</c>.</exception>
/// <seealso cref="TakeFromInstancePoolDelegate{TInstance}"/>
/// <seealso cref="ReturnToInstancePoolDelegate{TInstance}"/>
publicstaticAsyncResourcePoolObservable<TResource,TimeSpan>CreateGenericTimeoutingResourcePool<TResource>(
thisAsyncResourceFactory<TResource>factory,
TakeFromInstancePoolDelegate<InstanceHolderWithTimestamp<AsyncResourceAcquireInfo<TResource>>>takeFromPool,
ReturnToInstancePoolDelegate<InstanceHolderWithTimestamp<AsyncResourceAcquireInfo<TResource>>>returnToPool
)=>newCachingAsyncResourcePoolWithTimeout<TResource>(
ArgumentValidator.ValidateNotNullReference(factory),
takeFromPool,
returnToPool
);
///// <summary>
///// This helper method will create a wrapper around this <see cref="ExplicitAsyncResourcePoolObservable{TResource}"/> which will expose only <see cref="AsyncResourcePoolObservable{TResource}"/> portion of its API.
///// </summary>
///// <typeparam name="TResource">The type of resource.</typeparam>
///// <param name="explicitPool">This <see cref="ExplicitAsyncResourcePoolObservable{TResource}"/>.</param>
///// <returns>An <see cref="AsyncResourcePoolObservable{TResource}"/> which will delegate the calls to this <see cref="ExplicitAsyncResourcePoolObservable{TResource}"/>.</returns>
///// <exception cref="NullReferenceException">If this <see cref="ExplicitAsyncResourcePoolObservable{TResource}"/> is <c>null</c>.</exception>
//public static AsyncResourcePoolObservable<TResource> WithoutExplicitAPI<TResource>( this ExplicitAsyncResourcePoolObservable<TResource> explicitPool )
// => new AsyncResourcePoolWrapper<TResource>( ArgumentValidator.ValidateNotNullReference( explicitPool ) );
///// <summary>
///// This helper method will create a wrapper around this <see cref="ExplicitAsyncResourcePoolObservable{TResource, TCleanUp}"/> which will expose only <see cref="AsyncResourcePoolObservable{TResource, TCleanUp}"/> portion of its API.
///// </summary>
///// <typeparam name="TResource">The type of resource.</typeparam>
///// <typeparam name="TCleanUp">The type of parameter for <see cref="AsyncResourcePoolCleanUp{TCleanUpParameter}.CleanUpAsync"/> method.</typeparam>
///// <param name="explicitPool">This <see cref="ExplicitAsyncResourcePoolObservable{TResource, TCleanUp}"/>.</param>
///// <returns>An <see cref="AsyncResourcePoolObservable{TResource, TCleanUp}"/> which will delegate the calls to this <see cref="ExplicitAsyncResourcePoolObservable{TResource, TCleanUp}"/>.</returns>
///// <exception cref="NullReferenceException">If this <see cref="ExplicitAsyncResourcePoolObservable{TResource, TCleanUp}"/> is <c>null</c>.</exception>
//public static AsyncResourcePoolObservable<TResource, TCleanUp> WithoutExplicitAPI<TResource, TCleanUp>( this ExplicitAsyncResourcePoolObservable<TResource, TCleanUp> explicitPool )
// => new CleanUpAsyncResourcePoolWrapper<TResource, TCleanUp>( ArgumentValidator.ValidateNotNullReference( explicitPool ) );
}