使用Parallel.ForEach(...)处理ManagementObjectCollection

时间:2015-07-23 12:17:58

标签: c# types parallel.foreach

我使用以下代码并行处理ManagementObjectCollection中的所有项目:

using (ManagementObjectCollection results = this._searcher.Get())
{
    // The type arguments for method Parallel.ForEach<TSource>(...) cannot be inferred from usage
    Parallel.ForEach(results, (mo, loopState) =>
    {
        // process mo
    });
}

如果我指定了一个类型,那么就会抱怨这个

using (ManagementObjectCollection results = this._searcher.Get())
{
    // Cannot convert from ManagementObjectCollection to [..].IEnumereable<ManagementObject>
    Parallel.ForEach<ManagementObject>(results, (mo, loopState) =>
    {
        // process mo
    });
}

我该如何正常工作?为什么第二个代码块不起作用(AFAICS,ManagementObjectCollection实现了IEnumerable,为什么它会抱怨)?

1 个答案:

答案 0 :(得分:1)

它实现了非通用IEnumerable接口,因此使其成为IEnumerable<object>,而不是IEnumerable<ManagementObject>

我建议使用Cast<T>进行投射,这将在您迭代时投射每个元素:

Parallel.ForEach(results.Cast<ManagementObject>(),
                (mo, loopState) =>
{
    // process mo
});

如果由于某种原因你需要强类型列表,你可以在之前投射它:

var managementObjects = results.Cast<ManagementObject>().ToList();
Parallel.ForEach(managementObjects, (mo, loopState) =>
{
    // process mo
});