问题描述:

I have a class where I'm spawning a couple of threads to do some work. Now i want the ability to stop the work in case of an event. The event handler sets a field in the spawned class say(Interrupted). In my delegate of my For-Each, I'm checking on this flag before proceeding with the next iteration.

public bool Interrupted { get; set; }

Parallel.ForEach(some collection){

if (Interrupted)

{

parallelLoopState.Break();

return;

}

else

DoSomething();

}

Now once Interrupted is set to true on the parent thread. Would it be visible to the threads spawned by Parallel.Foreach right away ? Or does it take some time for it to have the visibilty ?

My tests intermittently fail, suggesting that even after the parent thread set the flag, the child threads executed a few times ?

Am i missing something basic ?

Is this a use case scenario of Volatile ?

网友答案:

You have parallel execution on the code block passed to the Parallel.ForEach method. So some threads will be just past the if (Interrupted) test when your main thread sets it to true. Only subsequent executions of the foreach loop will catch it.

网友答案:

I would not make any assumptions about the visibility of changes to Interrupted in other threads. You simply have to assume the worst. You will have to add explicit synchronization to guarantee that changes to the property are immediately visible to the Parallel looping construct.

Now with that said I suspect the observation that "the child threads executed a few times" is the result of a race between setting Interrupted and reading it. Remember, Parallel.ForEach will likely have many threads performing the work so all of them that made it past the read before it is changed will still continue to execute DoSomething.

相关阅读:
Top