1
- using System . Runtime . CompilerServices ;
1
+ using System ;
2
+ using System . Diagnostics ;
3
+ using System . Runtime . CompilerServices ;
4
+ using System . Threading ;
5
+ using System . Threading . Tasks ;
2
6
using DotJEM . Json . Index2 . Documents ;
3
7
using DotJEM . Json . Index2 . Documents . Info ;
4
8
using DotJEM . ObservableExtensions . InfoStreams ;
5
9
using Lucene . Net . Index ;
6
10
using Newtonsoft . Json . Linq ;
11
+ using static DotJEM . Json . Index2 . Management . Writer . JsonIndexWriter ;
7
12
8
13
namespace DotJEM . Json . Index2 . Management . Writer ;
9
14
@@ -24,16 +29,17 @@ public class JsonIndexWriter : IJsonIndexWriter
24
29
private readonly ILuceneDocumentFactory mapper ;
25
30
private readonly IFieldInformationManager resolver ;
26
31
private readonly IInfoStream < JsonIndexManager > infoStream = new InfoStream < JsonIndexManager > ( ) ;
27
-
32
+ private readonly ThrottledCommit throttledCommit ;
33
+
28
34
private IndexWriter Writer => index . WriterManager . Writer ;
29
-
30
35
public IInfoStream InfoStream => infoStream ;
31
36
32
37
public JsonIndexWriter ( IJsonIndex index )
33
38
{
34
39
this . index = index ;
35
40
this . mapper = index . Configuration . DocumentFactory ;
36
41
this . resolver = index . Configuration . FieldInformationManager ;
42
+ throttledCommit = new ThrottledCommit ( this ) ;
37
43
}
38
44
39
45
public void Update ( JObject entity )
@@ -61,7 +67,8 @@ public void Delete(JObject entity)
61
67
62
68
public void Commit ( )
63
69
{
64
- Writer . Commit ( ) ;
70
+ throttledCommit . Invoke ( ) ;
71
+ //Writer.Commit();
65
72
DebugInfo ( $ "Writer.Commit()") ;
66
73
}
67
74
@@ -79,4 +86,44 @@ public void MaybeMerge()
79
86
80
87
private void DebugInfo ( string message , [ CallerMemberName ] string caller = null )
81
88
=> infoStream . WriteDebug ( message , caller ) ;
89
+
90
+ public class ThrottledCommit
91
+ {
92
+ private readonly JsonIndexWriter target ;
93
+ private readonly WaitHandle handle = new AutoResetEvent ( false ) ;
94
+ private readonly long upperBound = Stopwatch . Frequency * 10 ;
95
+ private readonly long lowerBound = Stopwatch . Frequency / 10 ;
96
+
97
+ private long lastInvocation = 0 ;
98
+ private long lastRequest = 0 ;
99
+
100
+ public ThrottledCommit ( JsonIndexWriter target )
101
+ {
102
+ this . target = target ;
103
+ ThreadPool . RegisterWaitForSingleObject ( handle , ( _ , _ ) => Tick ( ) , null , 200 , false ) ;
104
+ }
105
+
106
+ private void Tick ( )
107
+ {
108
+ long time = Stopwatch . GetTimestamp ( ) ;
109
+ if ( time - lastInvocation > upperBound )
110
+ {
111
+ target . Writer . Commit ( ) ;
112
+ lastInvocation = time ;
113
+ return ;
114
+ }
115
+
116
+ if ( time - lastRequest > lowerBound )
117
+ {
118
+ target . Writer . Commit ( ) ;
119
+ lastInvocation = time ;
120
+ }
121
+ }
122
+
123
+ public void Invoke ( )
124
+ {
125
+ lastRequest = Stopwatch . GetTimestamp ( ) ;
126
+ Tick ( ) ;
127
+ }
128
+ }
82
129
}
0 commit comments