44using System . Diagnostics ;
55using System . Threading ;
66using System . Threading . Tasks ;
7+ using SMLogging . Properties ;
78
89namespace SMLogging
910{
@@ -24,8 +25,7 @@ public BackgroundFileTraceListener(string path)
2425 {
2526 FlushInterval = 5000 ;
2627 MaxFlushSize = 1000 ;
27-
28- _queue = new ConcurrentQueue < Event > ( ) ;
28+ MaxQueueSize = 10000 ;
2929 }
3030
3131 /// <summary>
@@ -38,8 +38,7 @@ public BackgroundFileTraceListener(string path, string name)
3838 {
3939 FlushInterval = 5000 ;
4040 MaxFlushSize = 1000 ;
41-
42- _queue = new ConcurrentQueue < Event > ( ) ;
41+ MaxQueueSize = 10000 ;
4342 }
4443
4544 #endregion
@@ -67,6 +66,15 @@ public BackgroundFileTraceListener(string path, string name)
6766 [ ConfigurationProperty ( "maxFlushSize" ) ]
6867 public int MaxFlushSize { get ; set ; }
6968
69+ /// <summary>
70+ /// Gets or sets the maximum size of the queue.
71+ /// </summary>
72+ /// <remarks>
73+ /// This value specifies the maximum number of events to queue. The default value is 10000.
74+ /// </remarks>
75+ [ ConfigurationProperty ( "maxQueueSize" ) ]
76+ public int MaxQueueSize { get ; set ; }
77+
7078 #endregion
7179
7280 #region Protected Properties
@@ -133,7 +141,7 @@ public override void Flush()
133141 {
134142 foreach ( var evt in events )
135143 {
136- _queue . Enqueue ( evt ) ;
144+ EnqueueEvent ( evt , false ) ;
137145 }
138146 }
139147 }
@@ -181,14 +189,38 @@ private void EnqueueEvent(TraceEventCache eventCache, string source, TraceEventT
181189 Message = message
182190 } ;
183191
184- _queue . Enqueue ( evt ) ;
192+ EnqueueEvent ( evt , true ) ;
185193
186194 if ( FlushInterval >= 0 && ! Trace . AutoFlush && ! IsBackgroundFlushing )
187195 {
188196 StartBackgroundFlushing ( ) ;
189197 }
190198 }
191199
200+ private void EnqueueEvent ( Event evt , bool force )
201+ {
202+ if ( _queue . Count >= MaxQueueSize )
203+ {
204+ if ( force )
205+ {
206+ Event oldEvt ;
207+ _queue . TryDequeue ( out oldEvt ) ;
208+ _queue . Enqueue ( evt ) ;
209+ }
210+
211+ if ( ! _maxQueueSizeReached )
212+ {
213+ _maxQueueSizeReached = true ;
214+ Fail ( AssemblyResources . MaxQueueSizeReached ) ;
215+ }
216+ }
217+ else
218+ {
219+ _queue . Enqueue ( evt ) ;
220+ _maxQueueSizeReached = false ;
221+ }
222+ }
223+
192224 private void StartBackgroundFlushing ( )
193225 {
194226 lock ( _workerLock )
@@ -231,9 +263,10 @@ private void StopBackgroundFlushing()
231263
232264 #region Private Fields
233265
234- private readonly ConcurrentQueue < Event > _queue ;
266+ private readonly ConcurrentQueue < Event > _queue = new ConcurrentQueue < Event > ( ) ;
235267 private CancellationTokenSource _workerCts ;
236268 private static readonly object _workerLock = new object ( ) ;
269+ private bool _maxQueueSizeReached = false ;
237270
238271 #endregion
239272
0 commit comments