patawa91
patawa91

Reputation: 46

Why Does Parallel.ForEachAsync Use All Threads On My Box Waiting Using AsyncManualResetEvent?

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);

Upvotes: 2

Views: 179

Answers (0)

Related Questions