@@ -9,8 +9,10 @@ namespace ZirconNet.Core.Async;
99/// </summary>
1010public sealed class AsyncTaskQueue
1111{
12+ private readonly EventWaitHandle waitHandle = new AutoResetEvent ( false ) ;
1213 private SemaphoreSlim _taskSemaphore ;
1314 private SemaphoreSlim _queueSemaphore ;
15+ private SemaphoreSlim _waitForFirst ;
1416 private int _tasksInQueue = 0 ;
1517 private readonly ConcurrentBag < Exception > _exceptions = new ( ) ;
1618
@@ -25,6 +27,7 @@ public AsyncTaskQueue(int maximumThreads = -1)
2527
2628 _taskSemaphore = new SemaphoreSlim ( maximumThreads ) ;
2729 _queueSemaphore = new SemaphoreSlim ( 0 , int . MaxValue ) ;
30+ _waitForFirst = new SemaphoreSlim ( 0 , int . MaxValue ) ;
2831 }
2932
3033 private async Task RunAction ( Func < Task > actionToRun , CancellationToken cancellationToken )
@@ -66,8 +69,13 @@ public async Task AddTaskAsync(Func<Task> actionToRun, CancellationToken cancell
6669 }
6770 }
6871
69- public async ValueTask WaitForQueueToEnd ( CancellationToken cancellationToken = default )
72+ public async ValueTask WaitForQueueToEnd ( bool waitForFirstTask = true , CancellationToken cancellationToken = default )
7073 {
74+ if ( waitForFirstTask )
75+ {
76+ await _waitForFirst . WaitAsync ( cancellationToken ) ;
77+ }
78+
7179 if ( _tasksInQueue > 0 )
7280 {
7381 await _queueSemaphore . WaitAsync ( cancellationToken ) ;
@@ -86,9 +94,11 @@ public async ValueTask Reset(int maximumThreads = -1)
8694 maximumThreads = Environment . ProcessorCount ;
8795 }
8896
89- _taskSemaphore = new SemaphoreSlim ( maximumThreads ) ;
90- _queueSemaphore = new SemaphoreSlim ( 0 , int . MaxValue ) ;
97+ _taskSemaphore = new ( maximumThreads ) ;
98+ _queueSemaphore = new ( 0 , int . MaxValue ) ;
99+ _waitForFirst = new ( 0 , int . MaxValue ) ;
91100 _tasksInQueue = 0 ;
92101 IsFaulted = false ;
102+ waitHandle . Reset ( ) ;
93103 }
94104}
0 commit comments