尝试在ConfigurationElementCollection上使用Parallel.ForEach。无法让它发挥作用

时间:2013-02-07 16:35:55

标签: c# app-config ienumerable ienumerator

我有一个自定义配置部分,其中包含我使用以下代码创建的集合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?

1 个答案:

答案 0 :(得分:0)

尝试

config.States.Cast<StateElement>()

而不是

config.States.GetEnumerator()