@@ -79,7 +79,6 @@ public void Delete(JObject entity)
79
79
public void Commit ( )
80
80
{
81
81
throttledCommit . Invoke ( ) ;
82
- //Writer.Commit();
83
82
DebugInfo ( $ "Writer.Commit()") ;
84
83
}
85
84
@@ -108,6 +107,7 @@ public class ThrottledCommit
108
107
private long lastInvocation = 0 ;
109
108
private long lastRequest = 0 ;
110
109
private long writes = 0 ;
110
+ private long calls = 0 ;
111
111
112
112
public ThrottledCommit ( JsonIndexWriter target )
113
113
{
@@ -137,6 +137,9 @@ private void Commit()
137
137
if ( Interlocked . Exchange ( ref writes , 0 ) < 1 )
138
138
return ;
139
139
140
+ if ( Interlocked . Exchange ( ref calls , 0 ) < 1 )
141
+ return ;
142
+
140
143
try
141
144
{
142
145
target . Writer . Commit ( ) ;
@@ -150,6 +153,7 @@ private void Commit()
150
153
151
154
public void Invoke ( )
152
155
{
156
+ Interlocked . Increment ( ref calls ) ;
153
157
lastRequest = Stopwatch . GetTimestamp ( ) ;
154
158
}
155
159
@@ -158,4 +162,65 @@ public void Increment()
158
162
Interlocked . Increment ( ref writes ) ;
159
163
}
160
164
}
165
+ }
166
+ public class ThrottledAction
167
+ {
168
+ private readonly Action target ;
169
+ private readonly Action < Exception > onException ;
170
+ private readonly WaitHandle handle = new AutoResetEvent ( false ) ;
171
+ private readonly long upperBound = Stopwatch . Frequency * 10 ;
172
+ private readonly long lowerBound = Stopwatch . Frequency / 5 ;
173
+
174
+ private long lastInvocation = 0 ;
175
+ private long lastRequest = 0 ;
176
+ private long writes = 0 ;
177
+
178
+ public ThrottledAction ( Action target , Action < Exception > onException )
179
+ {
180
+ this . target = target ;
181
+ this . onException = onException ;
182
+ ThreadPool . RegisterWaitForSingleObject ( handle , ( _ , _ ) => Tick ( ) , null , 200 , false ) ;
183
+ }
184
+
185
+ private void Tick ( )
186
+ {
187
+ long time = Stopwatch . GetTimestamp ( ) ;
188
+ if ( time - lastInvocation > upperBound )
189
+ {
190
+ Commit ( ) ;
191
+ lastInvocation = time ;
192
+ return ;
193
+ }
194
+
195
+ if ( time - lastRequest > lowerBound )
196
+ {
197
+ Commit ( ) ;
198
+ lastInvocation = time ;
199
+ }
200
+ }
201
+
202
+ private void Commit ( )
203
+ {
204
+ if ( Interlocked . Exchange ( ref writes , 0 ) < 1 )
205
+ return ;
206
+
207
+ try
208
+ {
209
+ target ( ) ;
210
+ }
211
+ catch ( Exception e )
212
+ {
213
+ onException ( e ) ;
214
+ }
215
+ }
216
+
217
+ public void Invoke ( )
218
+ {
219
+ lastRequest = Stopwatch . GetTimestamp ( ) ;
220
+ }
221
+
222
+ public void Increment ( )
223
+ {
224
+ Interlocked . Increment ( ref writes ) ;
225
+ }
161
226
}
0 commit comments