Does C# Parallel.ForEach use the same thread for i

2019-06-19 02:12发布

问题:

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.

回答1:

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.