【问题标题】:Trying to use Parallel.ForEach on a ConfigurationElementCollection. Can't get it to work尝试在 ConfigurationElementCollection 上使用 Parallel.ForEach。无法让它工作
【发布时间】:2013-01-23 06:02:47
【问题描述】:

我有一个自定义配置部分,其中包含我使用从 question 获得的以下代码创建的集合:

public class GenericConfigurationElementCollection<T> : ConfigurationElementCollection, IEnumerable<T> where T : ConfigurationElement, new()
{
    List<T> _elements = new List<T>();

    protected override ConfigurationElement CreateNewElement()
    {
        T newElement = new T();
        _elements.Add(newElement);
        return newElement;
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return _elements.Find(e => e.Equals(element));
    }

    public new IEnumerator<T> GetEnumerator()
    {
        return _elements.GetEnumerator();
    }
}

我使用如下属性实现了我的集合:

    [ConfigurationProperty("states")]
    [ConfigurationCollection(typeof(StateElement))]
    public GenericConfigurationElementCollection<StateElement> States
    {
        get
        {
            return (GenericConfigurationElementCollection<StateElement>)this["states"];
        }
    }

问题是,当我尝试使用 Parallel.ForEach 遍历集合时,如下所示

Parallel.ForEach<StateElement>(config.States.GetEnumerator(), state=> theState.StateStatus(state));

我收到以下错误:

The best overloaded method match for 'System.Threading.Tasks.Parallel.ForEach<States.Configuration.StateElement>(System.Collections.Generic.IEnumerable<States.Configuration.StateElement>, System.Action<States.Configuration.StateElement>)' has some invalid arguments   
Argument 1: cannot convert from 'System.Collections.Generic.IEnumerator<States.Configuration.StateElement>' to 'System.Collections.Generic.IEnumerable<States.Configuration.StateElement>'

最后一个让我难过。无法从 IEnumerator 转换为 IEnumerable?

【问题讨论】:

    标签: c# app-config ienumerable ienumerator


    【解决方案1】:

    试试

    config.States.Cast<StateElement>()
    

    而不是

    config.States.GetEnumerator()
    

    【讨论】:

    • 这给了我一个错误“无法从'方法组'转换为'System.Collections.Generic.IEnumerable
    • 对不起,我误解了你的第一个例外。只需使用对我有用的 config.States,如果它仍然无法正常工作,请将代码发送给我,我会很乐意提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2016-02-24
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多