From a63d56b0b4764859eae0246ebfdfb2b089a381f3 Mon Sep 17 00:00:00 2001 From: sakno Date: Sat, 13 Jul 2024 20:19:48 +0300 Subject: [PATCH] Corner case with empty set of tasks --- .../Tasks/TaskCompletionPipe.Consumer.cs | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/src/DotNext.Threading/Threading/Tasks/TaskCompletionPipe.Consumer.cs b/src/DotNext.Threading/Threading/Tasks/TaskCompletionPipe.Consumer.cs index 8c1ed11f4..95e1c3475 100644 --- a/src/DotNext.Threading/Threading/Tasks/TaskCompletionPipe.Consumer.cs +++ b/src/DotNext.Threading/Threading/Tasks/TaskCompletionPipe.Consumer.cs @@ -1,8 +1,11 @@ using System.Runtime.InteropServices; +using DotNext.Collections.Generic; using Debug = System.Diagnostics.Debug; namespace DotNext.Threading.Tasks; +using static Collections.Generic.AsyncEnumerable; + /// /// Provides various extension methods for class. /// @@ -16,7 +19,7 @@ public static class TaskCompletionPipe /// The asynchronous consuming collection. public static Consumer GetConsumer(this TaskCompletionPipe> pipe) => new(pipe); - + /// /// Gets a collection over tasks to be available as they complete. /// @@ -25,9 +28,19 @@ public static Consumer GetConsumer(this TaskCompletionPipe> pipe) /// A collection over task results to be available as they complete. public static Consumer GetConsumer(this ReadOnlySpan> tasks) { - var pipe = new TaskCompletionPipe>(); - pipe.Add(tasks, complete: true); - return new(pipe); + Consumer result; + if (tasks.IsEmpty) + { + result = default; + } + else + { + var pipe = new TaskCompletionPipe>(); + pipe.Add(tasks, complete: true); + result = new(pipe); + } + + return result; } /// @@ -39,9 +52,20 @@ public static Consumer GetConsumer(this ReadOnlySpan> tasks) public static IAsyncEnumerable Create(ReadOnlySpan tasks) where T : Task { - var pipe = new TaskCompletionPipe(); - pipe.Add(tasks, complete: true); - return pipe; + IAsyncEnumerable result; + + if (tasks.IsEmpty) + { + result = Empty(); + } + else + { + var pipe = new TaskCompletionPipe(); + pipe.Add(tasks, complete: true); + result = pipe; + } + + return result; } private static async IAsyncEnumerator GetAsyncEnumerator(TaskCompletionPipe> pipe, uint expectedVersion, CancellationToken token) @@ -75,6 +99,6 @@ internal Consumer(TaskCompletionPipe> pipe) /// The token that can be used to cancel the operation. /// The asynchronous enumerator over completed tasks. public IAsyncEnumerator GetAsyncEnumerator(CancellationToken token = default) - => GetAsyncEnumerator(pipe, pipe.Version, token); + => pipe is null ? Empty().GetAsyncEnumerator(token) : GetAsyncEnumerator(pipe, pipe.Version, token); } } \ No newline at end of file