Skip to content

Commit

Permalink
Add Ignore() extension to ignore the results of a Task
Browse files Browse the repository at this point in the history
  • Loading branch information
lukebakken committed Nov 22, 2023
1 parent 26696ef commit 9c37140
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions projects/RabbitMQ.Client/client/TaskExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ internal static class TaskExtensions
{
#if !NET6_0_OR_GREATER
private static readonly TaskContinuationOptions s_tco = TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously;
private static void continuation(Task t, object s) => t.Exception.Handle(e => true);
private static void IgnoreTaskContinuation(Task t, object s) => t.Exception.Handle(e => true);
#endif

public static Task TimeoutAfter(this Task task, TimeSpan timeout)
Expand Down Expand Up @@ -68,12 +68,7 @@ static async Task DoTimeoutAfter(Task task, TimeSpan timeout)
Task resultTask = await Task.WhenAny(task, delayTask).ConfigureAwait(false);
if (resultTask == delayTask)
{
Task supressErrorTask = task.ContinueWith(
continuationAction: continuation,
state: null,
cancellationToken: CancellationToken.None,
continuationOptions: s_tco,
scheduler: TaskScheduler.Default);
task.Ignore();
throw new TimeoutException();
}
else
Expand Down Expand Up @@ -112,12 +107,7 @@ static async ValueTask DoTimeoutAfter(ValueTask valueTask, TimeSpan timeout)
Task resultTask = await Task.WhenAny(task, delayTask).ConfigureAwait(false);
if (resultTask == delayTask)
{
Task supressErrorTask = task.ContinueWith(
continuationAction: continuation,
state: null,
cancellationToken: CancellationToken.None,
continuationOptions: s_tco,
scheduler: TaskScheduler.Default);
task.Ignore();
throw new TimeoutException();
}
else
Expand Down Expand Up @@ -155,5 +145,26 @@ public static void EnsureCompleted(this ValueTask task)
{
task.GetAwaiter().GetResult();
}

#if !NET6_0_OR_GREATER
// https://github.com/dotnet/runtime/issues/23878
// https://github.com/dotnet/runtime/issues/23878#issuecomment-1398958645
public static void Ignore(this Task task)
{
if (task.IsCompleted)
{
_ = task.Exception;
}
else
{
_ = task.ContinueWith(
continuationAction: IgnoreTaskContinuation,
state: null,
cancellationToken: CancellationToken.None,
continuationOptions: s_tco,
scheduler: TaskScheduler.Default);
}
}
#endif
}
}

0 comments on commit 9c37140

Please sign in to comment.