请问C#Parallel.ForEach使用同一个线程来收集的迭代 [英] Does C# Parallel.ForEach use the same thread for iterations of the collection

查看:124
本文介绍了请问C#Parallel.ForEach使用同一个线程来收集的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IEnumerable,我想传递给Parallel.ForEach,但IEnumerable的是使用C#的方法和产量,并有可能在枚举器代码不是线程安全的实现。计划使用Parallel.ForEach这一点。我的假设通过的ForEach了IEnumerable的实际内部迭代总是相同线程上,然后给ForEach传递每个项目的潜在其他线程的处理下。这是正确的?

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?

我读到哪里IEnumerable的迭代使用线程本地存储和不同的线程访问相同的IEnumerable将每个人都有自己的迭代当前,旁边等,这是为什么我假设的ForEach实际上将完成所有的同一线程上的迭代。

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.

我至少知道迭代是不一样的线程的Parallel.ForEach是调用。有点希望是因为我需要做一些线程初始化为正在做迭代的线程。因此,可能有一个问题在这里注入我初始化的线程执行迭代上。

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.

推荐答案

这是的无法写的的IEnumerator ,可以安全地从多个线程重复。该API本质上是反对允许这样的行为。因为这个Parallel.ForEach的没有可能的选择,但可以从一个单一的线程列举的顺序。为了迭代器直接暴露到每个产生的线程它需要使用比的IEnumerator / 的IEnumerable 揭露。

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.

这篇关于请问C#Parallel.ForEach使用同一个线程来收集的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆