1

This is what my loop looks like:

var loopResult = Parallel.ForEach(folder.Items.Cast<object>(), (item, loopState) =>
    {
        if (!loadData)
        {
            loopState.Stop();
            return;
        }

        DoSomeWork(item);
    }
);

if (loopResult.IsCompleted)
{
    Debug.WriteLine("done");
}

The problem is the code never gets to if (loopResult.IsCompleted). After executing return; for all the different threads, absolutely nothing happens.

2
  • 1
    What is happening inside DoSomeWork? Commented Mar 31, 2012 at 12:03
  • that is actually the right question to ask, it got stuck in that method trying to Invoke a method call on GUI thread, which never returned. Commented Apr 2, 2012 at 15:26

2 Answers 2

4

The code never gets to the body of if (loopResult.IsCompleted) because the parallel loop has been stopped successfully. You can check it as follows:

/* ForEach loop as above */

if (!loopResult.IsCompleted && 
         !loopResult.LowestBreakIteration.HasValue)
{
   Debug.WriteLine("Loop was stopped");
}

if (loopResult.IsCompleted)
{
    Debug.WriteLine("Loop was done without stopping");
}

You can find useful information how to Stop/Break a parallel loop in this MSDN page, starting from Breaking Out of Loops Early subsection.

Sign up to request clarification or add additional context in comments.

Comments

2

According to this, IsCompleted will not return true if a loop was ended prematurely:

Gets whether the loop ran to completion, such that all iterations of the loop were executed and the loop didn't receive a request to end prematurely.

Your call to Stop() causes all other loops to exit early, resulting in IsCompleted evaluating to false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.