将foreach循环改为Parallel.ForEach循环

7

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

目前代码如下:

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

我希望能够使用Parallel.ForEach函数。我想知道如何设置它。我尝试将表达式设置为现在的样子,但是我得到了一个错误,指出对象类型正在被用作变量。如果您能提供任何帮助,将不胜感激。

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

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

我现在遇到如下错误:
错误15:方法“System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner,System.Action)”的类型参数无法从用法中推断出来。请尝试明确指定类型参数。
有什么想法吗?谢谢你们的帮助,非常感激。
好的,我找到了这个网站: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
});

现在它可以无错误运行。万岁。

2
请发布您修改后的代码(即出现错误信息的代码)。 - Eric J.
编辑后:现在它取决于folder.Items和/或//做一些事情 - H H
2个回答

8

类似这样的:

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 接口。

1
+1 还要求实现 IEnumerable 接口。 - Eric J.
1
@ericj:这源于 for(item in Items) ... 的语法。 - H H

4
假设这是正确的。
foreach (Object item in folder.Items)
   Process(item);

然后它会变成:
Parallel.ForEach (folder.Items, item => Process(item));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接