@@ -39,7 +39,7 @@ internal static class TaskExtensions
3939 {
4040#if ! NET6_0_OR_GREATER
4141 private static readonly TaskContinuationOptions s_tco = TaskContinuationOptions . OnlyOnFaulted | TaskContinuationOptions . ExecuteSynchronously ;
42- private static void continuation ( Task t , object s ) => t . Exception . Handle ( e => true ) ;
42+ private static void IgnoreTaskContinuation ( Task t , object s ) => t . Exception . Handle ( e => true ) ;
4343#endif
4444
4545 public static Task TimeoutAfter ( this Task task , TimeSpan timeout )
@@ -68,12 +68,7 @@ static async Task DoTimeoutAfter(Task task, TimeSpan timeout)
6868 Task resultTask = await Task . WhenAny ( task , delayTask ) . ConfigureAwait ( false ) ;
6969 if ( resultTask == delayTask )
7070 {
71- Task supressErrorTask = task . ContinueWith (
72- continuationAction : continuation ,
73- state : null ,
74- cancellationToken : CancellationToken . None ,
75- continuationOptions : s_tco ,
76- scheduler : TaskScheduler . Default ) ;
71+ task . Ignore ( ) ;
7772 throw new TimeoutException ( ) ;
7873 }
7974 else
@@ -112,12 +107,7 @@ static async ValueTask DoTimeoutAfter(ValueTask valueTask, TimeSpan timeout)
112107 Task resultTask = await Task . WhenAny ( task , delayTask ) . ConfigureAwait ( false ) ;
113108 if ( resultTask == delayTask )
114109 {
115- Task supressErrorTask = task . ContinueWith (
116- continuationAction : continuation ,
117- state : null ,
118- cancellationToken : CancellationToken . None ,
119- continuationOptions : s_tco ,
120- scheduler : TaskScheduler . Default ) ;
110+ task . Ignore ( ) ;
121111 throw new TimeoutException ( ) ;
122112 }
123113 else
@@ -155,5 +145,26 @@ public static void EnsureCompleted(this ValueTask task)
155145 {
156146 task . GetAwaiter ( ) . GetResult ( ) ;
157147 }
148+
149+ #if ! NET6_0_OR_GREATER
150+ // https://github.com/dotnet/runtime/issues/23878
151+ // https://github.com/dotnet/runtime/issues/23878#issuecomment-1398958645
152+ public static void Ignore ( this Task task )
153+ {
154+ if ( task . IsCompleted )
155+ {
156+ _ = task . Exception ;
157+ }
158+ else
159+ {
160+ _ = task . ContinueWith (
161+ continuationAction : IgnoreTaskContinuation ,
162+ state : null ,
163+ cancellationToken : CancellationToken . None ,
164+ continuationOptions : s_tco ,
165+ scheduler : TaskScheduler . Default ) ;
166+ }
167+ }
168+ #endif
158169 }
159170}
0 commit comments