@@ -457,6 +457,34 @@ internal static void SetTimeoutExceptionWithState<TState>(
457457 cancellationToken : CancellationToken . None ) ;
458458 }
459459
460+ internal static void WaitForCompletion (
461+ Task task ,
462+ int timeoutInSeconds ,
463+ Action onTimeout = null ,
464+ bool rethrowExceptions = true )
465+ {
466+ try
467+ {
468+ task . Wait ( timeoutInSeconds > 0 ? 1000 * timeoutInSeconds : Timeout . Infinite ) ;
469+ }
470+ catch ( AggregateException ae )
471+ {
472+ if ( rethrowExceptions )
473+ {
474+ Debug . Assert ( ae . InnerException is not null , "Inner exception is null" ) ;
475+ Debug . Assert ( ae . InnerExceptions . Count == 1 , "There is more than one exception in AggregateException" ) ;
476+ ExceptionDispatchInfo . Capture ( ae . InnerException ) . Throw ( ) ;
477+ }
478+ }
479+
480+ if ( ! task . IsCompleted )
481+ {
482+ //Ensure the task does not leave an unobserved exception
483+ task . ContinueWith ( static t => { var ignored = t . Exception ; } ) ;
484+ onTimeout ? . Invoke ( ) ;
485+ }
486+ }
487+
460488 private record ContinuationState (
461489 Action OnCancellation ,
462490 Action < Exception > OnFailure ,
@@ -477,26 +505,5 @@ private record ContinuationState<TState1, TState2>(
477505 TState1 State1 ,
478506 TState2 State2 ,
479507 TaskCompletionSource < object > TaskCompletionSource ) ;
480-
481- internal static void WaitForCompletion ( Task task , int timeout , Action onTimeout = null , bool rethrowExceptions = true )
482- {
483- try
484- {
485- task . Wait ( timeout > 0 ? ( 1000 * timeout ) : Timeout . Infinite ) ;
486- }
487- catch ( AggregateException ae )
488- {
489- if ( rethrowExceptions )
490- {
491- Debug . Assert ( ae . InnerExceptions . Count == 1 , "There is more than one exception in AggregateException" ) ;
492- ExceptionDispatchInfo . Capture ( ae . InnerException ) . Throw ( ) ;
493- }
494- }
495- if ( ! task . IsCompleted )
496- {
497- task . ContinueWith ( static t => { var ignored = t . Exception ; } ) ; //Ensure the task does not leave an unobserved exception
498- onTimeout ? . Invoke ( ) ;
499- }
500- }
501508 }
502509}
0 commit comments