Does C # use Parallel.ForEach the same thread to iterate through the collection

I have an IEnumerable that I want to pass to Parallel.ForEach, but IEnumerable is implemented using the C # and yield method, and maybe the code in the enumerator is not thread safe. Planned to use Parallel.ForEach on this. I believe that the actual internal iteration of IEnumerable on ForEach is always in the same thread, and then ForEach passes each element to a potential different thread for processing. Is it correct?

I read where IEnumerable iteration uses local thread storage, and different threads accessing the same IEnumerable will have their own current iterative current, next, etc. This is why I assume that ForEach will actually do the entire iteration in the same thread.

At least I know that iteration is not in the same thread as Parallel.ForEach. Hope this was because I need to initialize the thread for the thread that iterates. Thus, a problem may arise in inserting my initialization into a thread that iterates.

+5
source share
1 answer

It is not possible to write an IEnumerator that can be safely repeated from multiple threads. The API, by its very nature, opposes this behavior. Because of this, Parallel.ForEach has no choice but to list a sequence from a single thread. To expose an iterator directly for each of the generated threads, it will need to use a different API than IEnumerator / IEnumerable shown.

+5
source

Source: https://habr.com/ru/post/1205463/


All Articles