Skip to main content
 首页 » 编程设计

c#之如何将 Parallel.ForEach 用于 Excel

2024年08月06日31TianFang

我正在尝试对 Excel 使用 Parallel.ForEach,但出现错误。代码是

using System.Threading.Tasks; 
using Excel = Microsoft.Office.Interop.Excel; 
 
public void function(Excel.Range range) 
{ 
    Parallel.ForEach(range, item=> 
    { 
        //do stuff 
    }); 
} 

错误是 错误 7:无法从用法中推断出方法“System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable, System.Action)”的类型参数。尝试明确指定类型参数。

如果您有任何想法,我将不胜感激。

请您参考如下方法:

您看到的错误是因为非通用集合不支持 Parallel.ForEach。

来自Parallel Programming in .NET blog :

.NET 2.0 introduced Generics to allow enhanced code reusability and type safety. Since then, generic collections (IEnumerable, List, Dictionary, etc.) have become standard and are recommended over their non-generic counterparts (IEnumerable, ArrayList, HashTable, etc.). As a result, Parallel.ForEach only supports generic collections, so code like the following will fail to compile.

有一个解决方法,使用他们在博客中提到的 IEnumerable.Cast:

Parallel.ForEach(r.Cast<object>(), _ => 
{ 
    // Do stuff 
}); 

虽然这将编译,但它不能与 Excel.Range 一起工作,因为它具有线程亲和性并且只能通过 STA 线程工作,因为它正在进行 COM 互操作。