Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# Parallel.ForEach use the same thread for iterations of the collection

I have an IEnumerable that I want to pass to Parallel.ForEach, but the IEnumerable is implemented using a C# method and yield, and potentially the code in enumerator is not thread safe. Was planning to use Parallel.ForEach on this. I am under the assumption that the actual internal iteration of the IEnumerable by ForEach is always on the same thread, and then the ForEach passes each item to a potential other thread for the processing. Is this correct?

I read where IEnumerable iteration uses thread local storage and different threads accessing the same IEnumerable will each have their own iteration current, next, etc. This is why I am assuming that the ForEach will actually do all the iteration on the same thread.

I at least know the iteration is not on the same thread that the Parallel.ForEach is called. Kinda hoping it was since I need to do some thread initialization for the thread that is doing the iteration. So may have an issue here to inject my initialization in on the thread doing the iteration.

like image 985
Ron Avatar asked Oct 24 '14 18:10

Ron


People also ask

What is the main cause of hep C?

Hepatitis C is a liver infection caused by the hepatitis C virus (HCV). Hepatitis C is spread through contact with blood from an infected person. Today, most people become infected with the hepatitis C virus by sharing needles or other equipment used to prepare and inject drugs.

Does hep C go away?

Hepatitis C virus (HCV) causes both acute and chronic infection. Acute HCV infections are usually asymptomatic and most do not lead to a life-threatening disease. Around 30% (15–45%) of infected persons spontaneously clear the virus within 6 months of infection without any treatment.

What does hep C pain feel like?

Many people with chronic HCV suffer from aches and pains in their joints. A variety of different joints can be involved but the most common are in the hands and wrists. These pains are often minor but occasionally the pain can be quite severe. In such cases painkillers can be used to relieve the symptoms.

How long can you have hep C without knowing?

Today, chronic HCV is usually curable with oral medications taken every day for two to six months. Still, about half of people with HCV don't know they're infected, mainly because they have no symptoms, which can take decades to appear.


1 Answers

It's impossible to write an IEnumerator that can safely be iterated from multiple threads. The API is inherently opposed to allowing such behavior. Because of this Parallel.ForEach has no possible choice but to enumerate the sequence from a single thread. In order to directly expose the iterator to each of the spawned threads it would need to use a different API than what IEnumerator/IEnumerable expose.

like image 182
Servy Avatar answered Sep 18 '22 12:09

Servy