加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:00:32 所属栏目:百科 来源:网络整理
导读:好的,这是基本背景.该程序连接到outlook / exchange并解析所有邮件消息以查看哪些是加密的.我想做的一件事是使用多线程来减少扫描消息所需的时间. 目前代码如下所示: foreach (Object item in folder.Items) {//Checks for encryption and gets needed info
好的,这是基本背景.该程序连接到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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读