为什么Parallel.ForeachAsync使用我的盒子上使用AsyncManualResetevent等待的所有线程?

发布于 2025-01-26 12:56:32 字数 1132 浏览 3 评论 0 原文

我要完成的工作是在处理其余的过程之前获得特定的记录。

不幸的是,在处理其余的之前,我没有自由列举两次以获取所需的1张记录。我确实知道我要寻找的记录将是枚举中的第一批记录之一,但我的理解是并行。foreachasync不能保证订单。

这是我如何在项目中使用它的缩小版本。从概念上讲,但更基础。我正在使用

如果运行它,它会冻结,因为它使用框上的所有可用线程。

我的想法是 waitasync 将允许线程进行其他工作。因此,我对 Parallel.ForeachAsync asyncManualResetevent 的理解是一个缺陷。

任何人都知道如何使用并行解决此问题。ForeachAsync或其他并行机制?

var mre = new AsyncManualResetEvent();
        await Parallel.ForEachAsync(Enumerable.Range(1, 1000), async (i, _) =>
        {
            Console.WriteLine("iteration {0}", i);
            if (i == 20)
            {
                Console.WriteLine("begin set {0}", i);
                mre.Set();
            }

            await mre.WaitAsync().ConfigureAwait(false);
            Console.WriteLine("released {0}", i);

            // Do work now that we have 20
        }).ConfigureAwait(false);

What I'm trying to accomplish is to get a particular record before I process the rest.

Unfortunately, I don't have the freedom to enumerate twice to get the 1 record I need before processing the rest. I do know that the record I'm looking for will be one of the first records from the Enumeration but my understanding is Parallel.ForEachAsync does not guarantee order.

This is a scaled down version of how I'm using it in my project. Conceptually the same, but more basic. I am using Microsoft VS for the AsyncManualResetEvent.

If you run it, it freezes because it uses all available threads on the box.

My thinking was that the WaitAsync would allow threads to do other work. So either a flaw in my understanding of Parallel.ForEachAsync or AsyncManualResetEvent.

Anyone know how to solve this using a Parallel.ForEachAsync or another Parallel mechanism?

var mre = new AsyncManualResetEvent();
        await Parallel.ForEachAsync(Enumerable.Range(1, 1000), async (i, _) =>
        {
            Console.WriteLine("iteration {0}", i);
            if (i == 20)
            {
                Console.WriteLine("begin set {0}", i);
                mre.Set();
            }

            await mre.WaitAsync().ConfigureAwait(false);
            Console.WriteLine("released {0}", i);

            // Do work now that we have 20
        }).ConfigureAwait(false);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文