微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 将foreach循环更改为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

原文地址:https://www.jb51.cc/csharp/100291.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐