@@ -18,6 +18,11 @@ namespace Microsoft.AspNet.Server.Kestrel
1818 /// </summary>
1919 public class KestrelThread
2020 {
21+ // maximum times the work queues swapped and are processed in a single pass
22+ // as completing a task may immediately have write data to put on the network
23+ // otherwise it needs to wait till the next pass of the libuv loop
24+ private const int _maxLoops = 8 ;
25+
2126 private static Action < object , object > _threadCallbackAdapter = ( callback , state ) => ( ( Action < KestrelThread > ) callback ) . Invoke ( ( KestrelThread ) state ) ;
2227 private KestrelEngine _engine ;
2328 private readonly IApplicationLifetime _appLifetime ;
@@ -249,11 +254,17 @@ private void ThreadStart(object parameter)
249254
250255 private void OnPost ( )
251256 {
252- DoPostWork ( ) ;
253- DoPostCloseHandle ( ) ;
257+ var loopsRemaining = _maxLoops ;
258+ bool wasWork ;
259+ do
260+ {
261+ wasWork = DoPostWork ( ) ;
262+ wasWork = DoPostCloseHandle ( ) || wasWork ;
263+ loopsRemaining -- ;
264+ } while ( wasWork && loopsRemaining > 0 ) ;
254265 }
255266
256- private void DoPostWork ( )
267+ private bool DoPostWork ( )
257268 {
258269 Queue < Work > queue ;
259270 lock ( _workSync )
@@ -262,6 +273,9 @@ private void DoPostWork()
262273 _workAdding = _workRunning ;
263274 _workRunning = queue ;
264275 }
276+
277+ bool wasWork = queue . Count > 0 ;
278+
265279 while ( queue . Count != 0 )
266280 {
267281 var work = queue . Dequeue ( ) ;
@@ -286,8 +300,10 @@ private void DoPostWork()
286300 }
287301 }
288302 }
303+
304+ return wasWork ;
289305 }
290- private void DoPostCloseHandle ( )
306+ private bool DoPostCloseHandle ( )
291307 {
292308 Queue < CloseHandle > queue ;
293309 lock ( _workSync )
@@ -296,6 +312,9 @@ private void DoPostCloseHandle()
296312 _closeHandleAdding = _closeHandleRunning ;
297313 _closeHandleRunning = queue ;
298314 }
315+
316+ bool wasWork = queue . Count > 0 ;
317+
299318 while ( queue . Count != 0 )
300319 {
301320 var closeHandle = queue . Dequeue ( ) ;
@@ -309,6 +328,8 @@ private void DoPostCloseHandle()
309328 throw ;
310329 }
311330 }
331+
332+ return wasWork ;
312333 }
313334
314335 private struct Work
0 commit comments