【问题标题】:C# AsyncEnumerable running/awaiting multiple tasks never finishesC# AsyncEnumerable 运行/等待多个任务永远不会完成
【发布时间】:2019-01-28 12:57:43
【问题描述】:

我想要一个接收Task<bool> 并在 X 任务中运行它的函数。

为此,我编写了以下代码:

public static class RetryComponent
{
    public static async Task RunTasks(Func<Task<bool>> action, int tasks, int retries, string method)
    {
        // Running everything
        var tasksPool = Enumerable.Range(0, tasks).Select(i => DoWithRetries(action, retries, method)).ToArray();
        await Task.WhenAll(tasksPool);
    }

    private static async Task<bool> DoWithRetries(Func<Task<bool>> action, int retryCount, string method)
    {
        while (true)
        {
            if (retryCount <= 0)
                return false;

            try
            {
                bool res = await action();
                if (res)
                    return true;
            }
            catch (Exception e)
            {
                // Log it
            }

            retryCount--;
            await Task.Delay(200); // retry in 200
        }
    }
}

以及如下执行代码:

BlockingCollection<int> ints = new BlockingCollection<int>();
foreach (int i in Enumerable.Range(0, 100000))
{
    ints.Add(i);
}
ints.CompleteAdding();

int taskId = 0;
var enumerable = new AsyncEnumerable<int>(async yield =>
{
    await RetryComponent.RunTasks(async () =>
    {
        try
        {
            int myTaskId = Interlocked.Increment(ref taskId);

            // usually there are async/await operations inside the while loop, this is just an example

            while (!ints.IsCompleted)
            {
                int number = ints.Take();

                Console.WriteLine($"Task {myTaskId}: {number}");
                await yield.ReturnAsync(number);
            }
        }
        catch (InvalidOperationException)
        {
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        return true;
    }, 10, 1, MethodBase.GetCurrentMethod().Name);
});

await enumerable.ForEachAsync(number =>
{
    Console.WriteLine(number);
});

AsyncEnumerable 来自System.Collections.Async

控制台显示任务 10:X(其中 x 是列表中的数字..)。

当我删除 AsyncEnumerable 时,一切都按预期工作(所有任务都在打印并且执行结束).. 出于某种原因,我很长时间都找不到,使用AsyncEnumerable 只会破坏一切(在我的主代码中,我需要它来使用AsyncEnumerable.. 可扩展性的东西..)这意味着代码永远不会停止,只有最后一个任务 (10) 正在打印。当我添加更多日志时,我发现任务 1-9 永远不会完成。

所以只是为了澄清问题,我想让多个任务执行异步操作并将结果生成给一个充当管道的 AsyncEnumerable 对象。 (这就是想法..)

【问题讨论】:

  • 它是如何毁掉一切的?
  • 因为当它不在 AsyncEnumerable 中时,事情会按预期工作并且所有任务都在打印(而不仅仅是任务 10。)另外,这个任务不会结束,因为任务 1-9 永远不会完成,原因是我不知道
  • 所以使用AsyncEnumerable,它只打印Task 10: {number}?请记住,在表述问题时,只有您了解其背后的背景,最好描述问题和预期/预期的解决方案以帮助我们理解。
  • 我想我现在说得更清楚了。

标签: c# multithreading async-await


【解决方案1】:

问题在于枚举器/生成器模式是顺序的,但您正在尝试执行多生产者、单一消费者模式。由于您使用嵌套匿名函数,并且堆栈溢出不显示行号,因此很难准确描述我指的是代码的哪一部分,但我还是会尝试。

AsyncEnumerable 的工作方式基本上是等待生产者产生一个值,然后等待消费者使用该值,然后重复。它不支持生产者和消费者以不同的速度运行,因此我说这种模式是顺序的。它没有生产项目队列only the current valueReturnAsync does not wait 供消费者使用该值,而不是您应该等待它返回的任务,这会给您一个信号,表明它已准备就绪。因此我们可以得出结论,它不是线程安全的。

但是,RetryComponent.RunTasks 并行运行 10 个任务,并且该代码调用 yield.ReturnAsync 而不检查是否有其他人已经调用它,如果是,则该任务是否已完成。由于 Yield 类仅存储当前值,因此您的 10 个并发任务会覆盖当前值,而无需等待 Yield 对象准备好接收新值,因此有 9 个任务会丢失并且永远不会等待。由于这 9 个任务永远不会等待,因此这些方法永远不会完成,Task.WhenAll 永远不会返回,整个调用堆栈中的任何其他方法也不会。

I created an issue on github 建议他们改进他们的库以在发生这种情况时抛出异常。如果他们实现它,您的 catch 块会将消息写入控制台并重新抛出错误,将任务置于故障状态,这将允许 task.WhenAll 完成,因此您的程序不会挂起。

您可以使用多线程同步 API 来确保一次只有一个任务调用 yield.ReturnAsync 并等待返回任务。或者您可以避免使用多生产者模式,因为单个生产者可以很容易地成为枚举器。否则,您将需要完全重新考虑如何实现多生产者模式。我建议 TPL Dataflow,它内置于 .NET Core 并在 .NET Framework 中作为 NuGet 包提供。

【讨论】:

  • 我他妈的知道这有什么不好。我检查我的代码的次数比我能数的要多。
【解决方案2】:

@zivkan 关于顺序生产者模式是绝对正确的。如果您想为单个流创建并发生产者,仍然可以使用 AsyncEnumerable 库来实现,但需要一些额外的代码。

这是一个解决并发生产者和消费者问题的示例(在这种情况下只有一个消费者):

        static void Main(string[] args)
        {
            var e = new AsyncEnumerable<int>(async yield =>
            {
                var threadCount = 10;
                var maxItemsOnQueue = 20;

                var queue = new ConcurrentQueue<int>();
                var consumerLimiter = new SemaphoreSlim(initialCount: 0, maxCount: maxItemsOnQueue + 1);
                var produceLimiter = new SemaphoreSlim(initialCount: maxItemsOnQueue, maxCount: maxItemsOnQueue);

                // Kick off producers
                var producerTasks = Enumerable.Range(0, threadCount)
                    .Select(index => Task.Run(() => ProduceAsync(queue, produceLimiter, consumerLimiter)));

                // When production ends, send a termination signal to the consumer.
                var endOfProductionTask = Task.WhenAll(producerTasks).ContinueWith(_ => consumerLimiter.Release());

                // The consumer loop.
                while (true)
                {
                    // Wait for an item to be produced, or a signal for the end of production.
                    await consumerLimiter.WaitAsync();

                    // Get a produced item.
                    if (queue.TryDequeue(out var item))
                    {
                        // Tell producers that they can keep producing.
                        produceLimiter.Release();
                        // Yield a produced item.
                        await yield.ReturnAsync(item);
                    }
                    else
                    {
                        // If the queue is empty, the production is over.
                        break;
                    }
                }
            });

            e.ForEachAsync((item, index) => Console.WriteLine($"{index + 1}: {item}")).Wait();
        }

        static async Task ProduceAsync(ConcurrentQueue<int> queue, SemaphoreSlim produceLimiter, SemaphoreSlim consumerLimiter)
        {
            var rnd = new Random();
            for (var i = 0; i < 10; i++)
            {
                await Task.Delay(10);
                var value = rnd.Next();

                await produceLimiter.WaitAsync(); // Wait for the next production slot
                queue.Enqueue(value); // Produce item on the queue
                consumerLimiter.Release(); // Notify the consumer
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2021-06-15
    相关资源
    最近更新 更多