c# - 将 foreach 循环更改为 Parallel.ForEach 循环

标签 c# parallel.foreach

好的,这是基本背景。该程序连接到 outlook/exchange 并解析所有邮件消息以查看哪些是加密的。我想做的一件事是使用多线程来减少扫描消息所需的时间。

目前代码如下所示:

foreach (Object item in folder.Items) {
//Checks for encryption and gets needed info and updates count
}

我想改用 Parallel.ForEach 函数。我想知道如何设置它。我尝试将表达式设置为现在的样子,但我收到一条错误消息,指出 Object 类型正被用作变量。如有任何帮助,我们将不胜感激。

好的,我得到的布局似乎是正确的。代码现在看起来像这样:

Parallel.ForEach(folder.Items, item =>
{
//does stuff
});

我现在收到以下错误:

Error 15 The type arguments for method System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner, System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

有什么想法吗?感谢您的帮助,非常感谢。

好的,我找到了这个网站:http://blogs.msdn.com/b/pfxteam/archive/2010/03/02/9971804.aspx它给了我我需要的错误答案。我只需要通过创建转换函数将集合更改为通用集合。

static IEnumerable<object> Cast(IEnumerable source)
{
    foreach (object o in source)
        yield return o;
}

然后将原来的调整为

Parallel.ForEach(Cast(folder.Items), item =>
{
//does stuff
});

现在它运行没有错误。欢呼吧。

最佳答案

像这样:

Parallel.For(0, folder.Items.Count - 1, delegate(int i) { 
  object item = folder.Items[i];
});

或者使用 ForEach:

Parallel.ForEach(folder.Items, item => {whatever you want to do with item})

注意:folder.Items 必须实现 IEnumerable

关于c# - 将 foreach 循环更改为 Parallel.ForEach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8217350/

相关文章:

c# - 需要帮助使 crc 计算的类线程安全

c# - 如何使用 Watin 关闭浏览器 (IE8)?

c# - OpenXML SDK 2.5 不可读的内容

c# - 使用 nhibernate 有什么方法可以在接口(interface)中映射只读属性

c# - Windows Azure 访问 App_Data

c# - 将数百万个项目从一个存储帐户移动到另一个存储帐户

c# - 并行的 AddOrUpdate 的 ConcurrentDictionary 和 ConcurrentBag

c# - 重载导致代码膨胀

.net-4.0 - 在并行调用中,限制每秒执行

c# - Parallel.ForEach 比正常的 foreach 慢