##// END OF EJS Templates
added object pool
cin -
r82:0363407ee75c v2
parent child
Show More
@@ -0,0 +1,85
1 using System;
2 using Implab.Parallels;
3 using System.Threading;
4
5 namespace Implab {
6 public class ObjectPool<T> : IDisposable {
7 readonly Func<T> m_factory;
8 readonly Action<T> m_cleanup;
9 readonly int m_size;
10 readonly MTQueue<T> m_queue = new MTQueue<T>();
11
12 volatile bool m_disposed;
13
14 volatile int m_count;
15
16 public ObjectPool(Func<T> factory, Action<T> cleanup, int size) {
17 Safe.ArgumentNotNull(factory, "factory");
18 Safe.ArgumentInRange(size, 1, size, "size");
19
20 m_factory = factory;
21 m_cleanup = cleanup;
22 m_size = size;
23 }
24
25 public ObjectPool(Func<T> factory, Action<T> cleanup) : this(factory,cleanup,Environment.ProcessorCount+1) {
26 }
27
28 public ObjectPool(Func<T> factory) : this(factory,null,Environment.ProcessorCount+1) {
29 }
30
31 public ObjectPoolWrapper<T> Allocate() {
32 if (m_disposed)
33 throw new ObjectDisposedException(this.ToString());
34
35 T instance;
36 if (m_queue.TryDequeue(out instance)) {
37 Interlocked.Decrement(ref m_count);
38 return instance;
39 } else {
40 instance = m_factory();
41 }
42 return new ObjectPoolWrapper<T>(instance, this);
43 }
44
45 public void Release(T instance) {
46 if (m_count < m_size && !m_disposed) {
47 Interlocked.Increment(ref m_count);
48
49 if (m_cleanup != null)
50 m_cleanup(instance);
51
52 m_queue.Enqueue(instance);
53
54 // пока элемент возвращался в кеш, была начата операция освобождения всего кеша
55 // и возможно уже законцена, в таком случае следует извлечь элемент обратно и
56 // освободить его. Если операция освобождения кеша еще не заврешилась, то будет
57 // изъят и освобожден произвольный элемен, что не повлияет на ход всего процесса.
58 if (m_disposed && m_queue.TryDequeue(out instance))
59 Safe.Dispose(instance);
60
61 } else {
62 Safe.Dispose(instance);
63 }
64 }
65
66 protected virtual void Dispose(bool disposing) {
67 if (disposing) {
68 m_disposed = true;
69 T instance;
70 while (m_queue.TryDequeue(out instance))
71 Safe.Dispose(instance);
72 }
73 }
74
75 #region IDisposable implementation
76
77 public void Dispose() {
78 Dispose(true);
79 GC.SuppressFinalize(this);
80 }
81
82 #endregion
83 }
84 }
85
@@ -0,0 +1,24
1 using System;
2
3 namespace Implab {
4 public struct ObjectPoolWrapper<T> : IDisposable {
5 readonly T m_value;
6 readonly ObjectPool<T> m_pool;
7
8 internal ObjectPoolWrapper(T value, ObjectPool<T> pool) {
9 m_value = value;
10 m_pool = pool;
11 }
12
13 public T Value {
14 get { return m_value; }
15 }
16
17 #region IDisposable implementation
18 public void Dispose() {
19 m_pool.Release(m_value);
20 }
21 #endregion
22 }
23 }
24
@@ -1,200 +1,198
1 1 <?xml version="1.0" encoding="utf-8"?>
2 2 <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3 3 <PropertyGroup>
4 4 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5 5 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
6 6 <ProjectGuid>{F550F1F8-8746-4AD0-9614-855F4C4B7F05}</ProjectGuid>
7 7 <OutputType>Library</OutputType>
8 8 <RootNamespace>Implab</RootNamespace>
9 9 <AssemblyName>Implab</AssemblyName>
10 <ProductVersion>8.0.30703</ProductVersion>
11 <SchemaVersion>2.0</SchemaVersion>
12 10 </PropertyGroup>
13 11 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
14 12 <DebugSymbols>true</DebugSymbols>
15 13 <DebugType>full</DebugType>
16 14 <Optimize>false</Optimize>
17 15 <OutputPath>bin\Debug</OutputPath>
18 16 <DefineConstants>TRACE;DEBUG;</DefineConstants>
19 17 <ErrorReport>prompt</ErrorReport>
20 18 <WarningLevel>4</WarningLevel>
21 19 <ConsolePause>false</ConsolePause>
22 20 <RunCodeAnalysis>true</RunCodeAnalysis>
23 21 </PropertyGroup>
24 22 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
25 23 <DebugType>full</DebugType>
26 24 <Optimize>true</Optimize>
27 25 <OutputPath>bin\Release</OutputPath>
28 26 <ErrorReport>prompt</ErrorReport>
29 27 <WarningLevel>4</WarningLevel>
30 28 <ConsolePause>false</ConsolePause>
31 29 </PropertyGroup>
32 30 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug 4.5|AnyCPU' ">
33 31 <DebugSymbols>true</DebugSymbols>
34 32 <DebugType>full</DebugType>
35 33 <Optimize>false</Optimize>
36 34 <OutputPath>bin\Debug</OutputPath>
37 35 <DefineConstants>TRACE;DEBUG;NET_4_5</DefineConstants>
38 36 <ErrorReport>prompt</ErrorReport>
39 37 <WarningLevel>4</WarningLevel>
40 38 <RunCodeAnalysis>true</RunCodeAnalysis>
41 39 <ConsolePause>false</ConsolePause>
42 40 </PropertyGroup>
43 41 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release 4.5|AnyCPU' ">
44 42 <Optimize>true</Optimize>
45 43 <OutputPath>bin\Release</OutputPath>
46 44 <ErrorReport>prompt</ErrorReport>
47 45 <WarningLevel>4</WarningLevel>
48 46 <ConsolePause>false</ConsolePause>
49 47 <DefineConstants>NET_4_5</DefineConstants>
50 48 </PropertyGroup>
51 49 <ItemGroup>
52 50 <Reference Include="System" />
53 51 <Reference Include="System.Xml" />
54 52 </ItemGroup>
55 53 <ItemGroup>
56 54 <Compile Include="Component.cs" />
57 55 <Compile Include="CustomEqualityComparer.cs" />
58 56 <Compile Include="Diagnostics\ConsoleTraceListener.cs" />
59 57 <Compile Include="Diagnostics\EventText.cs" />
60 58 <Compile Include="Diagnostics\IEventTextFormatter.cs" />
61 59 <Compile Include="Diagnostics\LogChannel.cs" />
62 60 <Compile Include="Diagnostics\LogicalOperation.cs" />
63 61 <Compile Include="Diagnostics\TextFileListener.cs" />
64 62 <Compile Include="Diagnostics\TextListenerBase.cs" />
65 63 <Compile Include="Diagnostics\TraceLog.cs" />
66 64 <Compile Include="Diagnostics\TraceContext.cs" />
67 65 <Compile Include="Diagnostics\TraceEvent.cs" />
68 66 <Compile Include="Diagnostics\TraceEventType.cs" />
69 67 <Compile Include="Disposable.cs" />
70 68 <Compile Include="ICancellable.cs" />
71 69 <Compile Include="IProgressHandler.cs" />
72 70 <Compile Include="IProgressNotifier.cs" />
73 71 <Compile Include="IPromiseT.cs" />
74 72 <Compile Include="IPromise.cs" />
75 73 <Compile Include="IServiceLocator.cs" />
76 74 <Compile Include="ITaskController.cs" />
77 75 <Compile Include="JSON\JSONElementContext.cs" />
78 76 <Compile Include="JSON\JSONElementType.cs" />
79 77 <Compile Include="JSON\JSONGrammar.cs" />
80 78 <Compile Include="JSON\JSONParser.cs" />
81 79 <Compile Include="JSON\JSONScanner.cs" />
82 80 <Compile Include="JSON\JsonTokenType.cs" />
83 81 <Compile Include="JSON\JSONWriter.cs" />
84 82 <Compile Include="JSON\JSONXmlReader.cs" />
85 83 <Compile Include="JSON\JSONXmlReaderOptions.cs" />
86 84 <Compile Include="JSON\StringTranslator.cs" />
87 85 <Compile Include="Parallels\DispatchPool.cs" />
88 86 <Compile Include="Parallels\ArrayTraits.cs" />
89 87 <Compile Include="Parallels\MTQueue.cs" />
90 88 <Compile Include="Parallels\WorkerPool.cs" />
91 89 <Compile Include="Parsing\Alphabet.cs" />
92 90 <Compile Include="Parsing\AlphabetBase.cs" />
93 91 <Compile Include="Parsing\AltToken.cs" />
94 92 <Compile Include="Parsing\BinaryToken.cs" />
95 93 <Compile Include="Parsing\CatToken.cs" />
96 94 <Compile Include="Parsing\CDFADefinition.cs" />
97 95 <Compile Include="Parsing\DFABuilder.cs" />
98 96 <Compile Include="Parsing\DFADefinitionBase.cs" />
99 97 <Compile Include="Parsing\DFAStateDescriptor.cs" />
100 98 <Compile Include="Parsing\DFAutomaton.cs" />
101 99 <Compile Include="Parsing\EDFADefinition.cs" />
102 100 <Compile Include="Parsing\EmptyToken.cs" />
103 101 <Compile Include="Parsing\EndToken.cs" />
104 102 <Compile Include="Parsing\EnumAlphabet.cs" />
105 103 <Compile Include="Parsing\Grammar.cs" />
106 104 <Compile Include="Parsing\IAlphabet.cs" />
107 105 <Compile Include="Parsing\IDFADefinition.cs" />
108 106 <Compile Include="Parsing\IVisitor.cs" />
109 107 <Compile Include="Parsing\ParserException.cs" />
110 108 <Compile Include="Parsing\Scanner.cs" />
111 109 <Compile Include="Parsing\StarToken.cs" />
112 110 <Compile Include="Parsing\SymbolToken.cs" />
113 111 <Compile Include="Parsing\Token.cs" />
114 112 <Compile Include="SafePool.cs" />
115 113 <Compile Include="ServiceLocator.cs" />
116 114 <Compile Include="TaskController.cs" />
117 115 <Compile Include="ProgressInitEventArgs.cs" />
118 116 <Compile Include="Properties\AssemblyInfo.cs" />
119 117 <Compile Include="Promise.cs" />
120 118 <Compile Include="Parallels\AsyncPool.cs" />
121 119 <Compile Include="Safe.cs" />
122 120 <Compile Include="ValueEventArgs.cs" />
123 121 <Compile Include="PromiseExtensions.cs" />
124 122 <Compile Include="TransientPromiseException.cs" />
125 123 <Compile Include="SyncContextPromise.cs" />
126 <Compile Include="SyncPool.cs" />
127 <Compile Include="SyncPoolWrapper.cs" />
124 <Compile Include="ObjectPool.cs" />
125 <Compile Include="ObjectPoolWrapper.cs" />
128 126 </ItemGroup>
129 127 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
130 128 <ItemGroup />
131 129 <ProjectExtensions>
132 130 <MonoDevelop>
133 131 <Properties>
134 132 <Policies>
135 133 <CSharpFormattingPolicy IndentSwitchBody="True" NamespaceBraceStyle="EndOfLine" ClassBraceStyle="EndOfLine" InterfaceBraceStyle="EndOfLine" StructBraceStyle="EndOfLine" EnumBraceStyle="EndOfLine" MethodBraceStyle="EndOfLine" ConstructorBraceStyle="EndOfLine" DestructorBraceStyle="EndOfLine" BeforeMethodDeclarationParentheses="False" BeforeMethodCallParentheses="False" BeforeConstructorDeclarationParentheses="False" NewLineBeforeConstructorInitializerColon="NewLine" NewLineAfterConstructorInitializerColon="SameLine" BeforeIndexerDeclarationBracket="False" BeforeDelegateDeclarationParentheses="False" NewParentheses="False" SpacesBeforeBrackets="False" inheritsSet="Mono" inheritsScope="text/x-csharp" scope="text/x-csharp" />
136 134 <TextStylePolicy FileWidth="120" EolMarker="Unix" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/x-csharp" />
137 135 <DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedHierarchical" ResourceNamePolicy="MSBuild" />
138 136 <TextStylePolicy FileWidth="120" TabsToSpaces="False" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="application/xml" />
139 137 <XmlFormattingPolicy inheritsSet="Mono" inheritsScope="application/xml" scope="application/xml" />
140 138 <TextStylePolicy FileWidth="120" TabsToSpaces="False" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/plain" />
141 139 <NameConventionPolicy>
142 140 <Rules>
143 141 <NamingRule Name="Namespaces" AffectedEntity="Namespace" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
144 142 <NamingRule Name="Types" AffectedEntity="Class, Struct, Enum, Delegate" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
145 143 <NamingRule Name="Interfaces" AffectedEntity="Interface" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
146 144 <RequiredPrefixes>
147 145 <String>I</String>
148 146 </RequiredPrefixes>
149 147 </NamingRule>
150 148 <NamingRule Name="Attributes" AffectedEntity="CustomAttributes" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
151 149 <RequiredSuffixes>
152 150 <String>Attribute</String>
153 151 </RequiredSuffixes>
154 152 </NamingRule>
155 153 <NamingRule Name="Event Arguments" AffectedEntity="CustomEventArgs" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
156 154 <RequiredSuffixes>
157 155 <String>EventArgs</String>
158 156 </RequiredSuffixes>
159 157 </NamingRule>
160 158 <NamingRule Name="Exceptions" AffectedEntity="CustomExceptions" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
161 159 <RequiredSuffixes>
162 160 <String>Exception</String>
163 161 </RequiredSuffixes>
164 162 </NamingRule>
165 163 <NamingRule Name="Methods" AffectedEntity="Methods" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
166 164 <NamingRule Name="Static Readonly Fields" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Protected, Public" NamingStyle="CamelCase" IncludeInstanceMembers="False" IncludeStaticEntities="True" />
167 165 <NamingRule Name="Fields (Non Private)" AffectedEntity="Field" VisibilityMask="Internal, Public" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
168 166 <NamingRule Name="ReadOnly Fields (Non Private)" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Public" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False" />
169 167 <NamingRule Name="Fields (Private)" AffectedEntity="Field, ReadonlyField" VisibilityMask="Private, Protected" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False">
170 168 <RequiredPrefixes>
171 169 <String>m_</String>
172 170 </RequiredPrefixes>
173 171 </NamingRule>
174 172 <NamingRule Name="Static Fields (Private)" AffectedEntity="Field" VisibilityMask="Private" NamingStyle="CamelCase" IncludeInstanceMembers="False" IncludeStaticEntities="True">
175 173 <RequiredPrefixes>
176 174 <String>_</String>
177 175 </RequiredPrefixes>
178 176 </NamingRule>
179 177 <NamingRule Name="ReadOnly Fields (Private)" AffectedEntity="ReadonlyField" VisibilityMask="Private, Protected" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False">
180 178 <RequiredPrefixes>
181 179 <String>m_</String>
182 180 </RequiredPrefixes>
183 181 </NamingRule>
184 182 <NamingRule Name="Constant Fields" AffectedEntity="ConstantField" VisibilityMask="VisibilityMask" NamingStyle="AllUpper" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
185 183 <NamingRule Name="Properties" AffectedEntity="Property" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
186 184 <NamingRule Name="Events" AffectedEntity="Event" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
187 185 <NamingRule Name="Enum Members" AffectedEntity="EnumMember" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
188 186 <NamingRule Name="Parameters" AffectedEntity="Parameter, LocalVariable" VisibilityMask="VisibilityMask" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
189 187 <NamingRule Name="Type Parameters" AffectedEntity="TypeParameter" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
190 188 <RequiredPrefixes>
191 189 <String>T</String>
192 190 </RequiredPrefixes>
193 191 </NamingRule>
194 192 </Rules>
195 193 </NameConventionPolicy>
196 194 </Policies>
197 195 </Properties>
198 196 </MonoDevelop>
199 197 </ProjectExtensions>
200 198 </Project> No newline at end of file
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now